Created
April 9, 2014 02:33
-
-
Save robinator/10220813 to your computer and use it in GitHub Desktop.
Add enum capabilities to your active record objects
This file contains 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
# this adds enum capibilities to an active record model | |
# http://jeffkreeftmeijer.com/2011/microgems-five-minute-rubygems/ | |
module ActiveRecordEnum | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
# how to define an enum on a model | |
# pass :prefix => true to prefix the ? methods with attribute name | |
def enum(attribute, choices, options = {}) | |
prefix = options[:prefix] ? "#{attribute}_" : '' | |
# add an 'attributes' method | |
define_singleton_method(:"#{attribute.to_s.pluralize}") { choices } | |
# add 'choice?' methods | |
choices.each do |choice| | |
define_method(:"#{prefix}#{choice}?") { send(attribute) == choice } | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send(:include, ActiveRecordEnum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment