Module: RESTFramework::Mixins::BaseModelControllerMixin::ClassMethods

Defined in:
lib/rest_framework/mixins/model_controller_mixin.rb

Constant Summary collapse

IGNORE_VALIDATORS_WITH_KEYS =
[:if, :unless].freeze

Instance Method Summary collapse

Instance Method Details

#field_configurationObject

Get a full field configuration, including defaults and inferred values.



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
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
241
242
243
244
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
# File 'lib/rest_framework/mixins/model_controller_mixin.rb', line 128

def field_configuration
  return @field_configuration if @field_configuration

  field_config = self.field_config&.with_indifferent_access || {}
  model = self.get_model
  columns = model.columns_hash
  column_defaults = model.column_defaults
  reflections = model.reflections
  attributes = model._default_attributes
  readonly_attributes = model.readonly_attributes
  exclude_body_fields = self.exclude_body_fields&.map(&:to_s)
  rich_text_association_names = model.reflect_on_all_associations(:has_one)
    .collect(&:name)
    .select { |n| n.to_s.start_with?("rich_text_") }
  attachment_reflections = model.attachment_reflections

  return @field_configuration = self.get_fields.map { |f|
    cfg = field_config[f]&.dup || {}
    cfg[:label] ||= self.label_for(f)

    # Annotate primary key.
    if model.primary_key == f
      cfg[:primary_key] = true

      unless cfg.key?(:readonly)
        cfg[:readonly] = true
      end
    end

    # Annotate readonly attributes.
    if f.in?(readonly_attributes) || f.in?(exclude_body_fields)
      cfg[:readonly] = true
    end

    # Annotate column data.
    if column = columns[f]
      cfg[:kind] = "column"
      cfg[:type] ||= column.type
      cfg[:required] = true unless column.null
    end

    # Add default values from the model's schema.
    if column_default = column_defaults[f] && !cfg[:default].nil?
      cfg[:default] ||= column_default
    end

    # Add metadata from the model's attributes hash.
    if attribute = attributes[f]
      if cfg[:default].nil? && default = attribute.value_before_type_cast
        cfg[:default] = default
      end
      cfg[:kind] ||= "attribute"

      # Get any type information from the attribute.
      if type = attribute.type
        cfg[:type] ||= type.type if type.type

        # Get enum variants.
        if type.is_a?(ActiveRecord::Enum::EnumType)
          cfg[:enum_variants] = type.send(:mapping)

          # TranslateEnum Integration:
          translate_method = "translated_#{f.pluralize}"
          if model.respond_to?(translate_method)
            cfg[:enum_translations] = model.send(translate_method)
          end
        end
      end
    end

    # Get association metadata.
    if ref = reflections[f]
      cfg[:kind] = "association"

      # Determine sub-fields for associations.
      if ref.polymorphic?
        ref_columns = {}
      else
        ref_columns = ref.klass.columns_hash
      end
      cfg[:sub_fields] ||= RESTFramework::Utils.sub_fields_for(ref)
      cfg[:sub_fields] = cfg[:sub_fields].map(&:to_s)

      # Very basic metadata about sub-fields.
      cfg[:sub_fields_metadata] = cfg[:sub_fields].map { |sf|
        v = {}

        if ref_columns[sf]
          v[:kind] = "column"
        else
          v[:kind] = "method"
        end

        next [sf, v]
      }.to_h.compact.presence

      # Determine if we render id/ids fields. Unfortunately, `has_one` does not provide this
      # interface.
      if self.permit_id_assignment && id_field = RESTFramework::Utils.id_field_for(f, ref)
        cfg[:id_field] = id_field
      end

      # Determine if we render nested attributes options.
      if self.permit_nested_attributes_assignment && (
        nested_opts = model.nested_attributes_options[f.to_sym].presence
      )
        cfg[:nested_attributes_options] = {field: "#{f}_attributes", **nested_opts}
      end

      begin
        cfg[:association_pk] = ref.active_record_primary_key
      rescue ActiveRecord::UnknownPrimaryKey
      end

      cfg[:reflection] = ref
    end

    # Determine if this is an ActionText "rich text".
    if :"rich_text_#{f}".in?(rich_text_association_names)
      cfg[:kind] = "rich_text"
    end

    # Determine if this is an ActiveStorage attachment.
    if ref = attachment_reflections[f]
      cfg[:kind] = "attachment"
      cfg[:attachment_type] = ref.macro
    end

    # Determine if this is just a method.
    if !cfg[:kind] && model.method_defined?(f)
      cfg[:kind] = "method"
    end

    # Collect validator options into a hash on their type, while also updating `required` based
    # on any presence validators.
    model.validators_on(f).each do |validator|
      kind = validator.kind
      options = validator.options

      # Reject validator if it includes keys like `:if` and `:unless` because those are
      # conditionally applied in a way that is not feasible to communicate via the API.
      next if IGNORE_VALIDATORS_WITH_KEYS.any? { |k| options.key?(k) }

      # Update `required` if we find a presence validator.
      cfg[:required] = true if kind == :presence

      # Resolve procs (and lambdas), and symbols for certain arguments.
      if options[:in].is_a?(Proc)
        options = options.merge(in: options[:in].call)
      elsif options[:in].is_a?(Symbol)
        options = options.merge(in: model.send(options[:in]))
      end

      cfg[:validators] ||= {}
      cfg[:validators][kind] ||= []
      cfg[:validators][kind] << options
    end

    next [f, cfg]
  }.to_h.with_indifferent_access
end

#get_fields(input_fields: nil) ⇒ Object

Get the available fields. Fallback to this controller’s model columns, or an empty array. This should always return an array of strings.



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
# File 'lib/rest_framework/mixins/model_controller_mixin.rb', line 99

def get_fields(input_fields: nil)
  input_fields ||= self.fields

  # If fields is a hash, then parse it.
  if input_fields.is_a?(Hash)
    return RESTFramework::Utils.parse_fields_hash(
      input_fields,
      self.get_model,
      exclude_associations: self.exclude_associations,
      action_text: self.enable_action_text,
      active_storage: self.enable_active_storage,
    )
  elsif !input_fields
    # Otherwise, if fields is nil, then fallback to columns.
    model = self.get_model
    return model ? RESTFramework::Utils.fields_for(
      model,
      exclude_associations: self.exclude_associations,
      action_text: self.enable_action_text,
      active_storage: self.enable_active_storage,
    ) : []
  elsif input_fields
    input_fields = input_fields.map(&:to_s)
  end

  return input_fields
end

#get_modelObject



79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/rest_framework/mixins/model_controller_mixin.rb', line 79

def get_model
  return @model if @model
  return (@model = self.model) if self.model

  # Try to determine model from controller name.
  begin
    return @model = self.name.demodulize.chomp("Controller").singularize.constantize
  rescue NameError
  end

  raise RESTFramework::UnknownModelError, self
end

#label_for(s) ⇒ Object

Override to include ActiveRecord i18n-translated column names.



93
94
95
# File 'lib/rest_framework/mixins/model_controller_mixin.rb', line 93

def label_for(s)
  return self.get_model.human_attribute_name(s, default: super)
end

#openapi_schemaObject



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
# File 'lib/rest_framework/mixins/model_controller_mixin.rb', line 290

def openapi_schema
  return @openapi_schema if @openapi_schema

  field_configuration = self.field_configuration
  @openapi_schema = {
    required: field_configuration.select { |_, cfg| cfg[:required] }.keys,
    type: "object",
    properties: field_configuration.map { |f, cfg|
      v = {title: cfg[:label]}

      if cfg[:kind] == "association"
        v[:type] = cfg[:reflection].collection? ? "array" : "object"
      elsif cfg[:kind] == "rich_text"
        v[:type] = "string"
        v[:"x-rrf-rich_text"] = true
      elsif cfg[:kind] == "attachment"
        v[:type] = "string"
        v[:"x-rrf-attachment"] = cfg[:attachment_type]
      else
        v[:type] = cfg[:type]
      end

      v[:readOnly] = true if cfg[:readonly]
      v[:default] = cfg[:default] if cfg.key?(:default)

      if enum_variants = cfg[:enum_variants]
        v[:enum] = enum_variants.keys
        v[:"x-rrf-enum_variants"] = enum_variants
      end

      if validators = cfg[:validators]
        v[:"x-rrf-validators"] = validators
      end

      v[:"x-rrf-kind"] = cfg[:kind] if cfg[:kind]

      if cfg[:reflection]
        v[:"x-rrf-reflection"] = cfg[:reflection]
        v[:"x-rrf-association_pk"] = cfg[:association_pk]
        v[:"x-rrf-sub_fields"] = cfg[:sub_fields]
        v[:"x-rrf-sub_fields_metadata"] = cfg[:sub_fields_metadata]
        v[:"x-rrf-id_field"] = cfg[:id_field]
        v[:"x-rrf-nested_attributes_options"] = cfg[:nested_attributes_options]
      end

      next [f, v]
    }.to_h,
  }

  return @openapi_schema
end

#rrf_finalizeObject

Define any behavior to execute at the end of controller definition. :nocov:



378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/rest_framework/mixins/model_controller_mixin.rb', line 378

def rrf_finalize
  super
  self.setup_delegation
  # self.setup_channel

  if RESTFramework.config.freeze_config
    self::RRF_BASE_MODEL_CONFIG.keys.each { |k|
      v = self.send(k)
      v.freeze if v.is_a?(Hash) || v.is_a?(Array)
    }
  end
end

#setup_delegationObject



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/rest_framework/mixins/model_controller_mixin.rb', line 342

def setup_delegation
  # Delegate extra actions.
  self.extra_actions&.each do |action, config|
    next unless config.is_a?(Hash) && config.dig(:metadata, :delegate)
    next unless self.get_model.respond_to?(action)

    self.define_method(action) do
      model = self.class.get_model

      if model.method(action).parameters.last&.first == :keyrest
        return render_api(model.send(action, **params))
      else
        return render_api(model.send(action))
      end
    end
  end

  # Delegate extra member actions.
  self.extra_member_actions&.each do |action, config|
    next unless config.is_a?(Hash) && config.dig(:metadata, :delegate)
    next unless self.get_model.method_defined?(action)

    self.define_method(action) do
      record = self.get_record

      if record.method(action).parameters.last&.first == :keyrest
        return render_api(record.send(action, **params))
      else
        return render_api(record.send(action))
      end
    end
  end
end