module ActiveRecord::VirtualEnumerations

Implements a mechanism to synthesize enum classes for simple enums. This is for situations where you wish to avoid cluttering the models directory with your enums.

Create a custom Rails initializer: Rails.root/config/initializers/virtual_enumerations.rb

ActiveRecord::VirtualEnumerations.define do |config|
  config.define 'ClassName',
                :table_name        => 'table',
                :extends           => 'SuperclassName',
                :conditions        => ['something = ?', "value"],
                :order             => 'column ASC',
                :on_lookup_failure => :enforce_strict,
                :name_column       => 'name_column',
                :alias_name        => false {
    # class_evaled_functions
  }
end

Only the ‘ClassName’ argument is required. :table_name is used to define a custom table name while the :extends option is used to set a custom superclass. Class names can be either camel-cased like ClassName or with underscores, like class_name. Strings and symbols are both fine.

If you need to fine-tune the definition of the enum class, you can optionally pass in a block, which will be evaluated in the context of the enum class.

Example:

config.define :color, :on_lookup_failure => :enforce_strict, do
  def to_argb(alpha)
    case self.to_sym
    when :white
      [alpha, 255, 255, 255]
    when :red
      [alpha, 255, 0, 0]
    when :blue
      [alpha, 0, 0, 255]
    when :yellow
      [alpha, 255, 255, 0]
    when :black
      [alpha, 0, 0, 0]
    end
  end
end

As a convenience, if multiple enums share the same configuration, you can pass all of them to config.define.

Example:

config.define :booking_status, :connector_type, :color, :order => :name

Single Table Inheritance is also supported:

Example:

config.define :base_enum, :name_column => ;foo
config.define :booking_status, :connector_type, :color, :extends => :base_enum