I'm trying to set some class variables to store paths in a Rails application (but I think this more a ruby question)
Basically my class looks like this
class Image < ActiveRecord::Base @@path_to_folder = "app/assets" @@images_folder = "upimages" @@path_to_images = File.join(@@path_to_folder, @@images_folder) end
But when I try to access @@path_to_images
from my controller by doing Image.path_to_images
, I get a NoMethodError
When I try with Image.class_eval( @@path_to_images )
, I get uninitialized class variable @@path_to_images in ImagesController
I've searched around and all I've seen says those would work, so I'm very confused about this
What's more, I tried defining simple classes with the ruby console like so
class Bidule @@foo = "foo" Bar = "bar" end
And so I tried, I think, all the ways possible (previous 2 included) to access them but no way I always get an exception raised
Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
Ruby has four types of variable scope, local, global, instance and class. In addition, Ruby has one constant type. Each variable type is declared by using a special character at the start of the variable name as outlined in the following table. In addition, Ruby has two pseudo-variables which cannot be assigned values.
Local Variables: A local variable name always starts with a lowercase letter(a-z) or underscore (_). These variables are local to the code construct in which they are declared. A local variable is only accessible within the block of its initialization. Local variables are not available outside the method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With