Skip to content

Instantly share code, notes, and snippets.

@d3r1v3d
Created March 13, 2011 04:05
Show Gist options
  • Save d3r1v3d/867855 to your computer and use it in GitHub Desktop.
Save d3r1v3d/867855 to your computer and use it in GitHub Desktop.
module EnumSupport
def enum(name, values)
const_name = name.to_s.pluralize.upcase
self.class_eval "
#{const_name} = %w{#{values.join(' ')}}.map{ |val| val.to_sym }
validates :#{name}, :presence => true,
:inclusion => {:in => #{const_name}, :message => self.bad_enum_message(#{const_name})}
def #{name}
read_attribute(:#{name}).to_sym
end
def #{name}=(value)
write_attribute :#{name}, value.to_s
end
"
end
protected
def bad_enum_message(enum)
"is not in the set (#{enum.join(', ')})"
end
end
class Radio < ActiveRecord::Base
extends EnumSupport
enum :mode, %w{am fm satellite cd mp3 other}
end
car_radio = Radio.new
car_radio.mode = :am
car_radio.valid? # true
car_radio.mode = :foo
car_radio.valid? # false
puts Radio::MODES # [:am, :fm, :satellite, :cd, :mp3, :other]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment