A handy enumerable to integer mapper creator
March 13, 2008
class EnumerableAttribute
attr_reader :values
def initialize(*args)
@values = Hash.new
0.upto(args.size-1) do |i|
@values[args[i].to_s] = i
end
@values.each do |key, value|
EnumerableAttribute.class_eval do
define_method key do
value
end
end
end
end
end
This class allows the dynamical creation of enumerable types mapped to integers in the database, starting from 0. The constructor will take a list of symbols representing the keys and will create a Hash that will map each key to one integer value. Once created, we can have access to the Hash via the method values or to the integer value of each key via the method called like the symbol.
E.g.
class Car
include EnumerableAttribute
end
>> engine_type = Car::EnumerableAttribute.new(:diesel, :gasoline, :solar)
=> #<EnumerableAttribute::EnumerableAttribute:0x2467f5c @values={"diesel"=>0, "gasoline"=>1, "solar" =>2}>
>> engine_type.values
=> {"diesel"=>0, "gasoline"=>1, "solar" =>2}
>> engine_type.gasoline
=> "1
Enjoy!
Advertisement
Hi,
I can’t understand how your code works. EnumerateAttribute is a class, Car is a class, and you include a class in a class. It’s not possible, as far as I know.
Hi Jean-Francois. What you include in the class is the module, not the class. The problem comes because the module and the class within have the same name, that is very bad. Yep, I should rename the class. Thank you!