Created
March 24, 2011 05:30
-
-
Save davidlee/884622 to your computer and use it in GitHub Desktop.
AR enums
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
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