Module: RESTFramework::BaseControllerMixin

Included in:
BaseModelControllerMixin
Defined in:
lib/rest_framework/controller_mixins/base.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 `api_response` is defined.

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

RRF_BASE_CONTROLLER_CONFIG =
{
  filter_pk_from_request_body: true,
  exclude_body_fields: [:created_at, :created_by, :updated_at, :updated_by],
  accept_generic_params_as_body_params: false,
  show_backtrace: false,
  extra_actions: nil,
  extra_member_actions: nil,
  filter_backends: nil,
  singleton_controller: nil,

  # Metadata and display options.
  title: nil,
  description: nil,
  inflect_acronyms: ["ID", "REST", "API"],

  # 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,
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



128
129
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/rest_framework/controller_mixins/base.rb', line 128

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

  base.extend(ClassMethods)

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

    base.class_attribute(a)

    # Set default manually so we can still support Rails 4. Maybe later we can use the default
    # parameter on `class_attribute`.
    base.send(:"#{a}=", default)
  end

  # Alias `extra_actions` to `extra_collection_actions`.
  unless base.respond_to?(:extra_collection_actions)
    base.alias_method(:extra_collection_actions, :extra_actions)
    base.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.
  base.rescue_from(ActiveRecord::RecordNotFound, with: :record_not_found)
  base.rescue_from(ActiveRecord::RecordInvalid, with: :record_invalid)
  base.rescue_from(ActiveRecord::RecordNotSaved, with: :record_not_saved)
  base.rescue_from(ActiveRecord::RecordNotDestroyed, with: :record_not_destroyed)
  base.rescue_from(ActiveModel::UnknownAttributeError, with: :unknown_attribute_error)

  # Use `TracePoint` hook to automatically call `rrf_finalize`.
  unless RESTFramework.config.disable_auto_finalize
    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
  end
end

Instance Method Details

#api_response(payload, html_kwargs: nil, **kwargs) ⇒ Object

Helper to 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.



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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/rest_framework/controller_mixins/base.rb', line 267

def api_response(payload, html_kwargs: nil, **kwargs)
  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 `api_response`). 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::NilPassedToAPIResponseError
  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 {
          jkwargs = kwargs.merge(json_kwargs)
          render(json: payload, layout: false, **jkwargs)
        } if self.class.serialize_to_json
        format.xml {
          xkwargs = kwargs.merge(xml_kwargs)
          render(xml: payload, layout: false, **xkwargs)
        } 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
        @template_logo_text ||= "Rails REST Framework"
        @title ||= self.class.get_title
        @description ||= self.class.description
        @route_props, @route_groups = RESTFramework::Utils.get_routes(
          Rails.application.routes, request
        )
        hkwargs = kwargs.merge(html_kwargs)
        begin
          render(**hkwargs)
        rescue ActionView::MissingTemplate  # Fallback to `rest_framework` layout.
          hkwargs[:layout] = "rest_framework"
          hkwargs[:html] = ""
          render(**hkwargs)
        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

#get_filter_backendsObject

Get filtering backends, defaulting to no backends.



202
203
204
# File 'lib/rest_framework/controller_mixins/base.rb', line 202

def get_filter_backends
  return self.class.filter_backends || []
end

#get_filtered_data(data) ⇒ Object

Filter an arbitrary data set over all configured filter backends.



207
208
209
210
211
212
213
214
# File 'lib/rest_framework/controller_mixins/base.rb', line 207

def get_filtered_data(data)
  self.get_filter_backends.each do |filter_class|
    filter = filter_class.new(controller: self)
    data = filter.get_filtered_data(data)
  end

  return data
end

#get_options_metadataObject



216
217
218
# File 'lib/rest_framework/controller_mixins/base.rb', line 216

def 
  return self.class.
end

#get_serializer_classObject

Get the configured serializer class.



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/rest_framework/controller_mixins/base.rb', line 179

def get_serializer_class
  return nil unless serializer_class = self.class.serializer_class

  # Support dynamically resolving serializer given a symbol or string.
  serializer_class = serializer_class.to_s if serializer_class.is_a?(Symbol)
  if serializer_class.is_a?(String)
    serializer_class = self.class.const_get(serializer_class)
  end

  # Wrap it with an adapter if it's an active_model_serializer.
  if defined?(ActiveModel::Serializer) && (serializer_class < ActiveModel::Serializer)
    serializer_class = RESTFramework::ActiveModelSerializerAdapterFactory.for(serializer_class)
  end

  return serializer_class
end

#optionsObject

Provide a generic `OPTIONS` response with metadata such as available actions.



346
347
348
# File 'lib/rest_framework/controller_mixins/base.rb', line 346

def options
  return api_response(self.)
end

#record_invalid(e) ⇒ Object



220
221
222
223
224
225
226
227
# File 'lib/rest_framework/controller_mixins/base.rb', line 220

def record_invalid(e)
  return api_response(
    {
      message: "Record invalid.", errors: e.record&.errors
    }.merge(self.class.show_backtrace ? {exception: e.full_message} : {}),
    status: 400,
  )
end

#record_not_destroyed(e) ⇒ Object



247
248
249
250
251
252
253
254
# File 'lib/rest_framework/controller_mixins/base.rb', line 247

def record_not_destroyed(e)
  return api_response(
    {
      message: "Record not destroyed.", errors: e.record&.errors
    }.merge(self.class.show_backtrace ? {exception: e.full_message} : {}),
    status: 400,
  )
end

#record_not_found(e) ⇒ Object



229
230
231
232
233
234
235
236
# File 'lib/rest_framework/controller_mixins/base.rb', line 229

def record_not_found(e)
  return api_response(
    {
      message: "Record not found.",
    }.merge(self.class.show_backtrace ? {exception: e.full_message} : {}),
    status: 404,
  )
end

#record_not_saved(e) ⇒ Object



238
239
240
241
242
243
244
245
# File 'lib/rest_framework/controller_mixins/base.rb', line 238

def record_not_saved(e)
  return api_response(
    {
      message: "Record not saved.", errors: e.record&.errors
    }.merge(self.class.show_backtrace ? {exception: e.full_message} : {}),
    status: 400,
  )
end

#rootObject

Default action for API root.



43
44
45
# File 'lib/rest_framework/controller_mixins/base.rb', line 43

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

#serialize(data, **kwargs) ⇒ Object

Serialize the given data using the `serializer_class`.



197
198
199
# File 'lib/rest_framework/controller_mixins/base.rb', line 197

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

#unknown_attribute_error(e) ⇒ Object



256
257
258
259
260
261
262
263
# File 'lib/rest_framework/controller_mixins/base.rb', line 256

def unknown_attribute_error(e)
  return api_response(
    {
      message: e.message.capitalize,
    }.merge(self.class.show_backtrace ? {exception: e.full_message} : {}),
    status: 400,
  )
end