Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to handle constants in Ruby when using Rails?

I have some constants that represent the valid options in one of my model's fields. What's the best way to handle these constants in Ruby?

like image 409
Miles Avatar asked Nov 05 '08 16:11

Miles


People also ask

Are constants global in Ruby?

Although constants look like local variables with capital letters, they have the visibility of global variables: they can be used anywhere in a Ruby program without regard to scope.

How do you convert a string to a constant in Ruby?

No need to require ActiveSupport. Usage example: class User; def self. lookup; const_get('SomeClassName);end; end User. lookup will return class itself.

Do not define constants this way within a block?

Overview. Do not define constants within a block, since the block's scope does not isolate or namespace the constant in any way. If you are trying to define that constant once, define it outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.


1 Answers

You can use an array or hash for this purpose (in your environment.rb):

OPTIONS = ['one', 'two', 'three'] OPTIONS = {:one => 1, :two => 2, :three => 3} 

or alternatively an enumeration class, which allows you to enumerate over your constants as well as the keys used to associate them:

class Enumeration   def Enumeration.add_item(key,value)     @hash ||= {}     @hash[key]=value   end    def Enumeration.const_missing(key)     @hash[key]   end       def Enumeration.each     @hash.each {|key,value| yield(key,value)}   end    def Enumeration.values     @hash.values || []   end    def Enumeration.keys     @hash.keys || []   end    def Enumeration.[](key)     @hash[key]   end end 

which you can then derive from:

class Values < Enumeration   self.add_item(:RED, '#f00')   self.add_item(:GREEN, '#0f0')   self.add_item(:BLUE, '#00f') end 

and use like this:

Values::RED    => '#f00' Values::GREEN  => '#0f0' Values::BLUE   => '#00f'  Values.keys    => [:RED, :GREEN, :BLUE] Values.values  => ['#f00', '#0f0', '#00f'] 
like image 196
Codebeef Avatar answered Oct 05 '22 14:10

Codebeef