Module: RESTFramework::Mixins::BaseControllerMixin

Included in:
BaseModelControllerMixin
Defined in:
lib/rest_framework/mixins/base_controller_mixin.rb

Overview

This module provides the common functionality for any controller mixins, a ‘root` action, and the ability to route arbitrary actions with `extra_actions`. This is also where `render_api` is implemented.

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

RRF_BASE_CONFIG =
{
  extra_actions: nil,
  extra_member_actions: nil,
  singleton_controller: nil,

  # Options related to metadata and display.
  title: nil,
  description: nil,
  version: nil,
  inflect_acronyms: ["ID", "IDs", "REST", "API", "APIs"].freeze,

  # Options related to serialization.
  rescue_unknown_format_with: :json,
  serializer_class: nil,
  serialize_to_json: true,
  serialize_to_xml: true,

  # Options related to pagination.
  paginator_class: nil,
  page_size: 20,
  page_query_param: "page",
  page_size_query_param: "page_size",
  max_page_size: nil,

  # Option to disable serializer adapters by default, mainly introduced because Active Model
  # Serializers will do things like serialize `[]` into `{"":[]}`.
  disable_adapters_by_default: true,

  # Custom integrations (reduces serializer performance due to method calls).
  enable_action_text: false,
  enable_active_storage: false,
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 74

def self.included(base)
  return unless base.is_a?(Class)

  base.extend(ClassMethods)

  # By default, the layout should be set to `rest_framework`.
  base.layout("rest_framework")

  # Add class attributes unless they already exist.
  RRF_BASE_CONFIG.each do |a, default|
    next if base.respond_to?(a)

    # Don't leak class attributes to the instance to avoid conflicting with action methods.
    base.class_attribute(a, default: default, instance_accessor: false)
  end

  # Alias `extra_actions` to `extra_collection_actions`.
  unless base.respond_to?(:extra_collection_actions)
    base.singleton_class.alias_method(:extra_collection_actions, :extra_actions)
    base.singleton_class.alias_method(:extra_collection_actions=, :extra_actions=)
  end

  # Skip CSRF since this is an API.
  begin
    base.skip_before_action(:verify_authenticity_token)
  rescue
    nil
  end

  # Handle some common exceptions.
  unless RESTFramework.config.disable_rescue_from
    base.rescue_from(
      ActionController::ParameterMissing,
      ActionController::UnpermittedParameters,
      ActiveRecord::AssociationTypeMismatch,
      ActiveRecord::NotNullViolation,
      ActiveRecord::RecordNotFound,
      ActiveRecord::RecordInvalid,
      ActiveRecord::RecordNotSaved,
      ActiveRecord::RecordNotDestroyed,
      ActiveRecord::RecordNotUnique,
      ActiveModel::UnknownAttributeError,
      with: :rrf_error_handler,
    )
  end

  # Use `TracePoint` hook to automatically call `rrf_finalize`.
  unless RESTFramework.config.disable_auto_finalize
    # :nocov:
    TracePoint.trace(:end) do |t|
      next if base != t.self

      base.rrf_finalize

      # It's important to disable the trace once we've found the end of the base class definition,
      # for performance.
      t.disable
    end
    # :nocov:
  end
end

Instance Method Details

#get_serializer_classObject



136
137
138
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 136

def get_serializer_class
  return self.class.serializer_class
end

#openapi_metadataObject



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 245

def 
  response_content_types = [
    "text/html",
    self.class.serialize_to_json ? "application/json" : nil,
    self.class.serialize_to_xml ? "application/xml" : nil,
  ].compact
  request_content_types = [
    "application/json",
    "application/xml",
    "application/x-www-form-urlencoded",
    "multipart/form-data",
  ].compact
  routes = self.route_groups.values[0]
  server = request.base_url + request.original_fullpath.gsub(/\?.*/, "")

  return {
    openapi: "3.1.1",
    info: {
      title: self.class.get_title,
      description: self.class.description,
      version: self.class.version.to_s,
    }.compact,
    servers: [{url: server}],
    paths: routes.group_by { |r| r[:concat_path] }.map { |concat_path, routes|
      [
        concat_path.gsub(/:([0-9A-Za-z_-]+)/, "{\\1}"),
        routes.map { |route|
           = route[:route].defaults[:metadata] || {}
          summary = [:label].presence || self.class.label_for(route[:action])
          description = [:description].presence
           = .except(:label, :description).presence

          [
            route[:verb].downcase,
            {
              summary: summary,
              description: description,
              responses: {
                200 => {
                  content: response_content_types.map { |ct|
                    [ct, {}]
                  }.to_h,
                  description: "",
                },
              },
              requestBody: route[:verb].in?(["GET", "DELETE", "OPTIONS", "TRACE"]) ? nil : {
                content: request_content_types.map { |ct|
                  [ct, {}]
                }.to_h,
              },
              "x-rrf-metadata": ,
            }.compact,
          ]
        }.to_h.merge(
          {
            parameters: routes.first[:route].required_parts.map { |p|
              {
                name: p,
                in: "path",
                required: true,
                schema: {type: "integer"},
              }
            },
          },
        ),
      ]
    }.to_h,
  }.compact
end

#optionsObject



315
316
317
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 315

def options
  render_api(self.)
end

#render_api(payload, **kwargs) ⇒ Object Also known as: api_response

Render a browsable API for ‘html` format, along with basic `json`/`xml` formats, and with support or passing custom `kwargs` to the underlying `render` calls.



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 171

def render_api(payload, **kwargs)
  html_kwargs = kwargs.delete(:html_kwargs) || {}
  json_kwargs = kwargs.delete(:json_kwargs) || {}
  xml_kwargs = kwargs.delete(:xml_kwargs) || {}

  # Raise helpful error if payload is nil. Usually this happens when a record is not found (e.g.,
  # when passing something like `User.find_by(id: some_id)` to `render_api`). The caller should
  # actually be calling `find_by!` to raise ActiveRecord::RecordNotFound and allowing the REST
  # framework to catch this error and return an appropriate error response.
  if payload.nil?
    raise RESTFramework::NilPassedToRenderAPIError
  end

  # If `payload` is an `ActiveRecord::Relation` or `ActiveRecord::Base`, then serialize it.
  if payload.is_a?(ActiveRecord::Base) || payload.is_a?(ActiveRecord::Relation)
    payload = self.serialize(payload)
  end

  # Do not use any adapters by default, if configured.
  if self.class.disable_adapters_by_default && !kwargs.key?(:adapter)
    kwargs[:adapter] = nil
  end

  # Flag to track if we had to rescue unknown format.
  already_rescued_unknown_format = false

  begin
    respond_to do |format|
      if payload == ""
        format.json { head(kwargs[:status] || :no_content) } if self.class.serialize_to_json
        format.xml { head(kwargs[:status] || :no_content) } if self.class.serialize_to_xml
      else
        format.json {
          render(json: payload, **kwargs.merge(json_kwargs))
        } if self.class.serialize_to_json
        format.xml {
          render(xml: payload, **kwargs.merge(xml_kwargs))
        } if self.class.serialize_to_xml
        # TODO: possibly support more formats here if supported?
      end
      format.html {
        @payload = payload
        if payload == ""
          @json_payload = "" if self.class.serialize_to_json
          @xml_payload = "" if self.class.serialize_to_xml
        else
          @json_payload = payload.to_json if self.class.serialize_to_json
          @xml_payload = payload.to_xml if self.class.serialize_to_xml
        end
        @title ||= self.class.get_title
        @description ||= self.class.description
        self.route_groups
        begin
          render(**kwargs.merge(html_kwargs))
        rescue ActionView::MissingTemplate
          # A view is not required, so just use `html: ""`.
          render(html: "", layout: true, **kwargs.merge(html_kwargs))
        end
      }
    end
  rescue ActionController::UnknownFormat
    if !already_rescued_unknown_format && rescue_format = self.class.rescue_unknown_format_with
      request.format = rescue_format
      already_rescued_unknown_format = true
      retry
    else
      raise
    end
  end
end

#rootObject

Default action for API root.



39
40
41
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 39

def root
  render_api({message: "This is the API root."})
end

#route_groupsObject



165
166
167
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 165

def route_groups
  return @route_groups ||= RESTFramework::Utils.get_routes(Rails.application.routes, request)
end

#rrf_error_handler(e) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 147

def rrf_error_handler(e)
  status = case e
  when ActiveRecord::RecordNotFound
    404
  else
    400
  end

  render_api(
    {
      message: e.message,
      errors: e.try(:record).try(:errors),
      exception: RESTFramework.config.show_backtrace ? e.full_message : nil,
    }.compact,
    status: status,
  )
end

#serialize(data, **kwargs) ⇒ Object

Serialize the given data using the ‘serializer_class`.



141
142
143
144
145
# File 'lib/rest_framework/mixins/base_controller_mixin.rb', line 141

def serialize(data, **kwargs)
  return RESTFramework::Utils.wrap_ams(self.get_serializer_class).new(
    data, controller: self, **kwargs
  ).serialize
end