Class: Cathode::IndexRequest

Inherits:
Request
  • Object
show all
Defined in:
lib/cathode/index_request.rb

Overview

Defines the default behavior for an index request.

Instance Attribute Summary

Attributes inherited from Request

#_body, #_status, #action, #context, #custom_logic, #resource

Instance Method Summary collapse

Methods inherited from Request

create, #initialize

Constructor Details

This class inherits a constructor from Cathode::Request

Instance Method Details

#default_action_blockObject

Determine the default action to use depending on the request. If the ‘page` param was passed and the action allows paging, page the results. Otherwise, set the request body to all records.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/cathode/index_request.rb', line 23

def default_action_block
  proc do
    all_records = model

    if allowed?(:paging) && params[:page]
      page = params[:page]
      per_page = params[:per_page] || 10
      lower_bound = (per_page - 1) * page
      upper_bound = lower_bound + per_page - 1

      body all_records[lower_bound..upper_bound]
    else
      body all_records
    end
  end
end

#modelObject

Determine the model to use depending on the request. If a sub-resource was requested, use the parent model to get the association. Otherwise, use all the resource’s model’s records.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/cathode/index_request.rb', line 7

def model
  if @resource_tree.size > 1
    parent_model_id = params["#{@resource_tree.first.name.to_s.singularize}_id"]
    model = @resource_tree.first.model.find(parent_model_id)
    @resource_tree.drop(1).each do |resource|
      model = model.send resource.name
    end
    model
  else
    super.all
  end
end