Module: CodyRobbins::DeclarativeFind::ClassMethods
- Defined in:
- lib/cody_robbins/declarative_find/class_methods.rb
Instance Method Summary collapse
-
#find(name, options = {}, &block) ⇒ Object
Creates a before filter on the controller that finds an ActiveRecord instance and assigns it to an instance variable.
Instance Method Details
#find(name, options = {}, &block) ⇒ Object
Creates a before filter on the controller that finds an ActiveRecord instance and assigns it to an instance variable.
- You pass the name of the model to look up to the method.
- By default the key in
paramsassumed to contain the ID of the record to find is either:idor, if:idis not present, then extrapolated from the model name. For example, if the model isUserthen this key would be:user. Preference is given to:idto prevent conflicts in situations such as edit actions, where a record is looked up but new values for its attributes are passed via a key inparamssharing the name of the model. For example, if the model isUserthenparams[:user]would contain the attributes for the user from the form, and:idwould have to be used to specify the ID of the user in question. - By default the instance variable that the record is assigned to will be named according to the model. For example, if the model is
Userthen the instance variable will be@user. - This behavior can be customized any which way via different combinations of options.
An 404 HTTP code will be returned and the corresponding error page rendered for non-existent records via the http-error gem.
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/cody_robbins/declarative_find/class_methods.rb', line 107 def find(name, = {}, &block) .reverse_merge!(:param => name, :variable => name, :using => "find_#{name}") model = name.to_class param_name = .delete(:param) variable_name = .delete(:variable) lookup_method = .delete(:using) before_filter() do object = if block_given? yield elsif lookup_method.is_a?(Proc) lookup_method.call elsif lookup_method.respond_to?(:to_s) && respond_to?(lookup_method.to_s) send(lookup_method.to_s) else id = params[:id] || params[param_name] model.find_by_id(id) end if object set_instance_variable(variable_name, object) else http_error(404) end end end |