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

2 Responses to “A handy enumerable to integer mapper creator”

  1. Jean-François Trân said

    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.

  2. kabish said

    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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.