Last active
March 21, 2018 12:06
-
-
Save slamotte/5185231 to your computer and use it in GitHub Desktop.
Allows ActiveResource to be used with shallow nested routes.
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 ShallowNestedRoutes | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
# Pass in the name of the parent class | |
def set_shallow_nested_route_parent(parent) | |
parent = parent.to_s | |
# Override these methods so they set the prefix path before a call and reset it afterward. | |
# This is used for shallow nested routes because ActiveRecord does not handle these well. | |
%w(all build create find_every).each do |method| | |
define_singleton_method(method.to_sym) do |*args| | |
old_prefix = self.prefix | |
self.prefix = "/#{parent.pluralize}/:#{parent}_id/" | |
begin | |
super(*args) # Return the result from calling the parent method | |
ensure | |
# Make sure prefix is reset when done | |
self.prefix = old_prefix | |
end | |
end | |
end | |
end | |
end | |
end | |
# Example usages | |
class SomeNestedResource < ActiveRecord::Base | |
include ShallowNestedRoutes | |
set_shallow_nested_route_parent :parent_resource | |
site = "http://localhost:3000" | |
# No need to fuss with prefix setting, overriding collection_path, etc. | |
end | |
SomeNestedResource.build(parent_id: @parent_id) | |
r = SomeNestedResource.create(parent_id: @parent_id, attr1: value1, attr2: value2, ...) | |
SomeNestedResource.find(r.id) | |
SomeNestedResource.all(params: {parent_id: @parent_id}) # Gross, but... | |
SomeNestedResource.find(:all, params: {parent_id: @parent_id}) | |
SomeNestedResource.first(params: {parent_id: @parent_id}) | |
SomeNestedResource.last(params: {parent_id: @parent_id}) | |
r.destroy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment