Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to access class variables in Ruby 1.9?

Tags:

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

like image 303
Geoffrey H Avatar asked Sep 25 '12 20:09

Geoffrey H


People also ask

How do I use a class variable in Ruby?

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.

How many types of variables are used in Ruby and what are they?

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.

What is a local variable Ruby?

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.


1 Answers

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 
like image 187
Soundar Rathinasamy Avatar answered Sep 23 '22 18:09

Soundar Rathinasamy