What is the proper way to access class variables in Ruby 1.9?
Rails provides class level attribute accessor for this functionality
Try
class Image < ActiveRecord::Base
cattr_accessor :path_to_folder
@@path_to_folder = "app/assets"
end
Then to access path_to_folder class variable just use
Image.path_to_folder
But people always suggest to avoid class variables due to its behavior in inheritance.So you can use constants like
class Image < ActiveRecord::Base
PATH_TO_FOLDER = "app/assets"
end
Then you can access the constant like
Image::PATH_TO_FOLDER
What can't I access class variable from object in ruby?
attr_accessor
creates methods to manipulate instance variables — it does not create instance or class variables. To create a class variable, you must set it to something:
@@shared_id = something
There's no helper method to generate accessor for class variables, so you have to write them yourself.
However, class variables, because of their weird lookup rules, are rarely used — avoided, even. Instead, instance variables at class-level are used.
class Service
@shared_id = thing
class << self
attr_accessor :shared_id
end
def system_id
# use self.class.shared_id; you could add a shared_id helper to generate it, too.
end
end
Can't access class variable in ruby/rails?
As written, you cannot. variable
is local to the instance method and can't be accessed by any Ruby expression from outside the method.
On a related point, the term "class variable" is typically used to refer to variables of the form @@variable
.
Update: In response to your "Edit" statement, if you change variable
to @@variable
in your class, then there are techniques available to access that variable from outside the class, but a naked reference to @@variable
isn't one of them. Carefully read the answers to the question you cited in your comment for more information.
Accessing Ruby Class Variables with class_eval and instance_eval
I just asked the same question to Matz during the RubyKaigi party. I was half-drunk, but he was perfectly sober, so you can take this as the definitive answer.
Anton is right - the reason why you cannot access class variables through instance_eval() is "just because". Even class_eval() shares the same issue (Matz himself wasn't totally sure about class_eval() until I told him I'd already tried it). More specifically: scope-wise, class variables are more like constants than instance variables, so switching self (as instance_eval() and class_eval() do) is not going to make any difference when it comes to accessing them.
In general, it might be a good idea to avoid class variables altogether.
Ruby: Accessing class instance variables from one class in another class's class method
If you want to create a new type of initializer for BClass, you can do the following:
class AClass
attr_accessor :avar
def initialize(input)
@avar = input
end
end
class BClass
attr_accessor :bvalue
def self.build(aclass)
bclass = self.new
bclass.bvalue = aclass.avar
bclass
end
end
aclass = AClass.new 'ruby'
bclass = BClass.build aclass
This will set bclass.bvalue = aclass.avar = 'ruby'.
Get class variable from class directly
Forwardable
is a better solution, but to provide another option, you could dynamically create the methods:
class A
def self.method_missing(name, *args, &blk)
define_singleton_method name.to_sym do
environment.send(name.to_sym)
end
self.send(name.to_sym)
end
end
I found my inspiration from here. This is works on Ruby 1.9.
how to access class instance variables VS class methods
Using Module#class_eval
or Object#instance_variable_get
.
class Test
@foo = nil
def self.foo foo
@foo = foo
end
end
Test.foo(12)
Test.class_eval('@foo') # => 12
Test.instance_variable_get('@foo') # => 12
Related Topics
Ruby Get Time in Given Timezone
Unable to Load Gem Cocoa Pods While Creating Repo
What Is a Worker in Ruby/Rails
Rake Db:Migrate Error with MySQL2 Gem - Library Not Loaded: Libssl.1.0.0.Dylib
How to Recursively Require All Files in a Directory in Ruby
How to Get a HTML Table Row with Capybara
Backspace and Arrow Keys Aren't Working in Irb(Git Bash Console) on Windows MAChine
Can't Run Jenkins Build - Bundle: "Command Not Found"
Ruby: Titleize: How to Ignore Smaller Words Like 'And', 'The', 'Or, etc
Routing Error - Uninitialized Constant
Checking Whether the C Compiler Works... No
How to Render a Plain HTML File with Sinatra
Stylesheet_Link_Tag :All Versus :Media =>All
Rails 4.1 Mailer Previews and Devise Custom Emails
Do You Know an Alternative Ctags Generator for Ruby