Skip to content

Instantly share code, notes, and snippets.

@tjk
Created July 7, 2012 19:36
Show Gist options
  • Save tjk/3067856 to your computer and use it in GitHub Desktop.
Save tjk/3067856 to your computer and use it in GitHub Desktop.
ActiveRecord#as_param
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
class Person < ActiveRecord::Base
as_param :name, { :in => :upcase, :out => :downcase } # methods called as value comes out / queries datastore
end
>> 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