Created
March 13, 2011 04:05
-
-
Save d3r1v3d/867855 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Radio < ActiveRecord::Base | |
extends EnumSupport | |
enum :mode, %w{am fm satellite cd mp3 other} | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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