Skip to content

Instantly share code, notes, and snippets.

@moro
Created February 22, 2011 04:50
Show Gist options
  • Save moro/838242 to your computer and use it in GitHub Desktop.
Save moro/838242 to your computer and use it in GitHub Desktop.
module TypeColumn
def type_column(column_name, types = nil)
types ||= const_get(column_name.to_s.pluralize.upcase)
raise if types.blank?
validates_inclusion_of column_name, :in => types
types.each do |t|
scope t, where(column_name => t)
class_eval(%[def #{t}?; #{column_name} == #{t.dump}; end], __FILE__, __LINE__)
end
end
end
class Note < ActiveRecord::Base
extend TypeColumn
CATEGORIES = %w[foo bar piyo]
type_column :category
end
Note.foo.all?{|n| n.foo? } # => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment