Skip to content

Instantly share code, notes, and snippets.

@robinator
Created April 9, 2014 02:33
Show Gist options
  • Save robinator/10220813 to your computer and use it in GitHub Desktop.
Save robinator/10220813 to your computer and use it in GitHub Desktop.
Add enum capabilities to your active record objects
# 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