Skip to content

Instantly share code, notes, and snippets.

@fizx
Created October 9, 2008 05:20
Show Gist options
  • Save fizx/15703 to your computer and use it in GitHub Desktop.
Save fizx/15703 to your computer and use it in GitHub Desktop.
# Put in initializers
#
# Usage:
# class Foo < ActiveRecord::Base
# finds_by :bar
# end
#
# foo = Foo.create(:bar => "omg")
# found = Foo.find "omg"
# assert_equal foo.id, found.id
#
class << ActiveRecord::Base
def finds_by(field_name)
eval %[
class << self
define_method :find_with_finds_by_#{field_name} do |*args|
first = args.first
if first.is_a?(String) && !(first =~ /^\d+$/)
find_without_finds_by_#{field_name}(:first, :conditions => { "#{field_name}" => first} )
else
find_without_finds_by_#{field_name}(*args)
end
end
alias_method_chain :find, :finds_by_#{field_name}
end
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment