Module: Pakyow::Routing::Extension::Resource::NestedResource

Defined in:
lib/pakyow/routing/extensions/resource.rb

Class Method Summary collapse

Class Method Details

.define(controller, nested_resource_id, nested_param) ⇒ Object

Nest resources as members of the current resource.



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/pakyow/routing/extensions/resource.rb', line 130

def self.define(controller, nested_resource_id, nested_param)
  unless controller.singleton_class.instance_methods(false).include?(:namespace)
    controller.define_singleton_method :namespace do |*args, &block|
      super(*args, &block).tap do |namespace|
        namespace.allow_params nested_param
        namespace.action :update_request_path_for_parent do
          connection.get(:__endpoint_path).gsub!("/#{nested_resource_id}", "")
        end
      end
    end
  end

  unless controller.singleton_class.instance_methods(false).include?(:resource)
    controller.define_singleton_method :resource do |name, matcher, param: DEFAULT_PARAM, &block|
      if existing_resource = children.find { |child| child.expansions.include?(:resource) && child.__object_name.name == name }
        existing_resource.instance_exec(&block); existing_resource
      else
        expand(:resource, name, File.join(nested_resource_id, matcher), param: param) do
          allow_params nested_param

          action :update_request_path_for_parent do
            connection.get(:__endpoint_path).gsub!("/#{nested_resource_id}", "")
          end

          class_eval(&block)
        end
      end
    end
  end
end