Skip to content

Instantly share code, notes, and snippets.

@tammersaleh
Created November 11, 2009 23:07
Show Gist options
  • Save tammersaleh/232415 to your computer and use it in GitHub Desktop.
Save tammersaleh/232415 to your computer and use it in GitHub Desktop.
module IdEnumeration
def acts_as_enumeration(*ordered_list_of_values)
ordered_list_of_values.map(&:to_s).each_with_index do |value, index|
const_set(value.upcase, index + 1)
self.class.send(:define_method, "find_#{value}!") do
find(const_get(value.upcase))
end
self.class.send(:define_method, "find_#{value}") do
find_by_id(const_get(value.upcase))
end
define_method "#{value}?" do
id == self.class.const_get(value.upcase)
end
end
end
end
ActiveRecord::Base.send(:extend, IdEnumeration)
class ProductState < ActiveRecord::Base
acts_as_enumeration :new, :active, :locked, :sold, :expired, :removed, :deleted
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment