Module: Rails::Surrender::ControllerAdditions

Defined in:
lib/rails/surrender/controller_additions.rb

Overview

Additions to the Rails ActionController to allow surrender’s rendering.

Instance Method Summary collapse

Instance Method Details

#initialize(*args) ⇒ Object



12
13
14
15
# File 'lib/rails/surrender/controller_additions.rb', line 12

def initialize(*args)
  @will_paginate = true
  super
end

#surrender(resource, status: 200, reload: true, include: [], exclude: []) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rails/surrender/controller_additions.rb', line 17

def surrender(resource, status: 200, reload: true, include: [], exclude: [])
  resource = filter resource if parsed_query_params.filter?

  if parsed_query_params.sort?
    resource = sort resource
    response.headers['X-Sort'] = parsed_query_params.sort.request
  end

  if paginate?(resource)
    resource = paginate resource
    response.headers['X-Pagination'] = pagination_headers(resource)
  end

  surrender_response = if parsed_query_params.count?
                         Render::Count.new(resource).parse
                       elsif parsed_query_params.ids?
                         Render::Ids.new(resource).parse
                       else
                         config = Render::Configuration.new(
                           resource_class: resource_class(resource),
                           reload_resource: reload,
                           user_exclude: parsed_query_params.exclude,
                           user_include: parsed_query_params.include,
                           ctrl_exclude: exclude,
                           ctrl_include: include
                         )

                         Render::Resource.new(resource: resource,
                                              ability: ability,
                                              config: config).parse
                       end

  # Allows the calling method to decorate the response data before returning the result
  surrender_response.data = yield surrender_response.data if block_given?

  render(json: surrender_response.json_data, status: status)
end