Created
November 15, 2012 21:30
-
-
Save bloudermilk/4081417 to your computer and use it in GitHub Desktop.
Idea for a nested resource controller helper
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
# Provides a helper method for controllers who need to query a nested resource. | |
# Implements per-request in-memory caching for nested resources as well as | |
# support for controllers that are also accessed without being nested. | |
module NestedResource | |
DEFAULT_OPTIONS = { | |
optional: false, | |
class_name: nil, | |
param: nil | |
} | |
# Defines a method named the same as the passed `name` on the calling class | |
# which returns the specified resource. | |
# | |
# Options (with defaults): | |
# * `optional`: *false* Set to true if ActiveSupport::RecordNotFound should be | |
# raised if a record can't be found. | |
# * `class_name`: *nil* Set to the name of a class you would like to search | |
# on. Defaults to a classified `name`. | |
# * `param`: *nil* Set to the key to check in `params` for the nested | |
# resource's `#id`. Defaults to the passed `name` with "_id" appended. | |
# | |
# Example: | |
# | |
# class OrdersController < ApplicationController | |
# extend NestedResource | |
# | |
# nested_resouce :user, optional: true | |
# | |
# def index | |
# @orders = user ? user.orders : [] | |
# end | |
# end | |
def nested_resource(name, options = {}) | |
options = options.reverse_merge(DEFAULT_OPTIONS) | |
# String#classify will be a noop on options[:class_name] | |
klass = (options[:class_name] || name.to_s).classify.constantize | |
ivar = "@#{name}" | |
param = options[:param] || "#{name}_id" | |
helper_method name | |
define_method name do | |
Rails.logger.info "lol" | |
if instance_variable_defined?(ivar) | |
instance_variable_get(ivar) | |
else | |
find_method = options[:optional] && !params[param] ? :find_by_id : :find | |
order = klass.send(find_method, params[param]) | |
instance_variable_set(ivar, order) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment