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
Rails provides class level attribute accessor for this functionality
Try
Then to access path_to_folder class variable just use
But people always suggest to avoid class variables due to its behavior in inheritance.So you can use constants like
Then you can access the constant like