Skip to content

Instantly share code, notes, and snippets.

@davidlee
Created March 24, 2011 05:30
Show Gist options
  • Save davidlee/884622 to your computer and use it in GitHub Desktop.
Save davidlee/884622 to your computer and use it in GitHub Desktop.
AR enums
module Quickfind
module ClassMethods
def quick_finder(field)
metaclass = class << self; self; end
klass = self
class_eval do
@@quickfinder = field
end
metaclass.class_eval do
klass.all.each do |record|
value = record.send(field)
define_method value do
klass.where(field => value).first
end
end
end
end
def [](k)
where(@@quickfinder => k).first
end
alias_method :%, :[]
end
end
# class User; quickfinder :username; end
# User[ username ] => finds a user by username
# class Unit; quickfinder :abbr; end
# Unit.CM => finds a unit by abbr
ActiveRecord::Base.extend Quickfind::ClassMethods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment