Created
July 7, 2012 19:36
-
-
Save tjk/3067856 to your computer and use it in GitHub Desktop.
ActiveRecord#as_param
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 AsParam | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def as_param(param, methods={}) | |
define_method :to_param do | |
value = send(param) | |
methods[:out] ? value.send(methods[:out]) : value | |
end | |
define_singleton_method :find do |*args| | |
value = args.shift | |
value = value.send(methods[:in]) if methods[:in] | |
self.send("find_by_#{param}", value, *args) | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send :include, AsParam |
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
class Person < ActiveRecord::Base | |
as_param :name, { :in => :upcase, :out => :downcase } # methods called as value comes out / queries datastore | |
end |
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
>> Person.all | |
=> [#<Person id: 1, name: "John">] | |
>> Person.first.to_param | |
=> "john" | |
>> Person.find("john") | |
=> #<Person id: 1, name: "John> | |
# essentially, | |
# with as_param.rb in config/initializers | |
# and with "resources :people" in config/routes | |
# we get: /person/:name routes | |
# and find(params[:id]) uses find_by_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment