Module: RESTFramework::Controller::ClassMethods
- Defined in:
- lib/rest_framework/controller.rb,
lib/rest_framework/controller/openapi.rb
Constant Summary collapse
- IGNORE_VALIDATORS_WITH_KEYS =
[ :if, :unless ].freeze
Instance Method Summary collapse
-
#field_configuration ⇒ Object
Get a full field configuration, including defaults and inferred values.
-
#get_fields(input_fields: nil) ⇒ Object
Get the available fields.
-
#get_title ⇒ Object
By default, this is the name of the controller class, titleized and with any custom inflection acronyms applied.
-
#label_for(s) ⇒ Object
Get a label from a field/column name, titleized and inflected.
- #openapi_document(request, route_group_name, routes) ⇒ Object
- #openapi_paths(routes, tag) ⇒ Object
- #openapi_request_content_types ⇒ Object
- #openapi_response_content_types ⇒ Object
-
#openapi_schema ⇒ Object
Only for model controllers.
-
#openapi_schema_name ⇒ Object
Only for model controllers.
-
#rrf_finalize ⇒ Object
Define any behavior to execute at the end of controller definition.
-
#setup_delegation ⇒ Object
Only for model controllers.
Instance Method Details
#field_configuration ⇒ Object
Get a full field configuration, including defaults and inferred values.
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 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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/rest_framework/controller.rb', line 182 def field_configuration return @field_configuration if @field_configuration field_config = self.field_config&.with_indifferent_access || {} columns = self.model.columns_hash column_defaults = self.model.column_defaults reflections = self.model.reflections attributes = self.model._default_attributes readonly_attributes = self.model.readonly_attributes read_only_fields = self.read_only_fields&.map(&:to_s)&.to_set || Set[] write_only_fields = self.write_only_fields&.map(&:to_s)&.to_set || Set[] hidden_fields = self.hidden_fields&.map(&:to_s)&.to_set || Set[] rich_text_association_names = self.model.reflect_on_all_associations(:has_one) .collect(&:name) .select { |n| n.to_s.start_with?("rich_text_") } = self.model. @field_configuration = self.get_fields.map { |f| cfg = field_config[f]&.dup || {} cfg[:label] ||= self.label_for(f) # Annotate primary key. if self.model.primary_key == f cfg[:primary_key] = true unless cfg.key?(:read_only) cfg[:read_only] = true end end # Annotate field mutability and display properties. cfg[:read_only] = true if f.in?(readonly_attributes) || f.in?(read_only_fields) cfg[:write_only] = true if f.in?(write_only_fields) cfg[:hidden] = true if f.in?(hidden_fields) # Raise warnings on some bad combinations of properties. if cfg[:write_only] if cfg[:read_only] Rails.logger.warn("RRF: `#{f}` write_only conflicts with read_only.") end if cfg[:hidden] Rails.logger.warn("RRF: `#{f}` write_only implies hidden.") end if cfg[:hidden_from_index] Rails.logger.warn("RRF: `#{f}` write_only implies hidden_from_index.") end 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 cfg[:default].nil? && (column_default = column_defaults[f]) cfg[:default] = column_default end # Add metadata from the model's attributes hash. if attributes.key?(f) && 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 self.model.respond_to?(translate_method) cfg[:enum_translations] = self.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 = self.model.[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 = [f] cfg[:kind] = "attachment" cfg[:attachment_type] = ref.macro end # Determine if this is just a method. if !cfg[:kind] && self.model.method_defined?(f) cfg[:kind] = "method" cfg[:read_only] = true if cfg[:read_only].nil? end # Collect validator options into a hash on their type, while also updating `required` based # on any presence validators. self.model.validators_on(f).each do |validator| kind = validator.kind = validator. # 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| .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 [:in].is_a?(Proc) = .merge(in: [:in].call) elsif [:in].is_a?(Symbol) = .merge(in: self.model.send([:in])) end cfg[:validators] ||= {} cfg[:validators][kind] ||= [] cfg[:validators][kind] << end next [ f, cfg ] }.to_h.compact.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.
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 |
# File 'lib/rest_framework/controller.rb', line 154 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.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. return self.model ? RESTFramework::Utils.fields_for( self.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 input_fields end |
#get_title ⇒ Object
By default, this is the name of the controller class, titleized and with any custom inflection acronyms applied.
122 123 124 125 126 127 |
# File 'lib/rest_framework/controller.rb', line 122 def get_title self.title || RESTFramework::Utils.inflect( self.name.demodulize.chomp("Controller").titleize(keep_id_suffix: true), self.inflect_acronyms, ) end |
#label_for(s) ⇒ Object
Get a label from a field/column name, titleized and inflected.
130 131 132 133 134 135 |
# File 'lib/rest_framework/controller.rb', line 130 def label_for(s) default_title = RESTFramework::Utils.inflect( s.to_s.titleize(keep_id_suffix: true), self.inflect_acronyms ) self.model&.human_attribute_name(s, default: default_title) || default_title end |
#openapi_document(request, route_group_name, routes) ⇒ Object
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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/rest_framework/controller/openapi.rb', line 102 def openapi_document(request, route_group_name, routes) server = request.base_url + request.original_fullpath.gsub(/\?.*/, "") { openapi: "3.1.1", info: { title: self.get_title, description: self.description, version: self.version.to_s, }.compact, servers: [ { url: server } ], paths: self.openapi_paths(routes, route_group_name), tags: [ { name: route_group_name, description: self.description }.compact ], components: { schemas: { "Error" => { type: "object", required: [ "message" ], properties: { message: { type: "string" }, errors: { type: "object" }, exception: { type: "string" }, }, }, }.merge(self.model ? { self.openapi_schema_name => self.openapi_schema } : {}), responses: { "BadRequest": { description: "Bad Request", content: self.openapi_response_content_types.map { |ct| [ ct, ct == "text/html" ? {} : { schema: { "$ref" => "#/components/schemas/Error" } }, ] }.to_h, }, "NotFound": { description: "Not Found", content: self.openapi_response_content_types.map { |ct| [ ct, ct == "text/html" ? {} : { schema: { "$ref" => "#/components/schemas/Error" } }, ] }.to_h, }, }, }, }.merge(self.model ? { "x-rrf-primary_key" => self.model.primary_key, "x-rrf-callbacks" => self._process_action_callbacks.as_json, # While bulk update/destroy are obvious because they create new router endpoints, bulk # create overloads the existing collection `POST` endpoint, so we add a special key to the # OpenAPI metadata to indicate bulk create is supported. "x-rrf-bulk-create": self.bulk, } : {}).compact end |
#openapi_paths(routes, tag) ⇒ Object
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 |
# File 'lib/rest_framework/controller/openapi.rb', line 19 def openapi_paths(routes, tag) resp_cts = self.openapi_response_content_types req_cts = self.openapi_request_content_types schema_name = self.openapi_schema_name if self.model routes.group_by { |r| r[:concat_path] }.map { |concat_path, routes| [ concat_path.gsub(/:([0-9A-Za-z_-]+)/, "{\\1}"), routes.map { |route| = RESTFramework::ROUTE_METADATA[route[:path]] || {} summary = .delete(:label).presence || self.label_for(route[:action]) description = .delete(:description).presence extra_action = RESTFramework::EXTRA_ACTION_ROUTES.include?(route[:path]) error_response = { "$ref" => "#/components/responses/BadRequest" } not_found_response = { "$ref" => "#/components/responses/NotFound" } spec = { tags: [ tag ], summary: summary, description: description }.compact # All routes should have a successful response. success_code = if !extra_action if route[:action] == "create" 201 elsif route[:action] == "destroy" 204 else 200 end else 200 end spec[:responses] = { success_code => { content: resp_cts.map { |ct| [ ct, (self.model && !extra_action && route[:verb] != "OPTIONS") ? { schema: { "$ref" => "#/components/schemas/#{schema_name}" }, } : {}, ] }.to_h, description: "Success", }, } # Builtin POST, PUT, PATCH, and DELETE should have a 400 and 404 response. if route[:verb].in?([ "POST", "PUT", "PATCH", "DELETE" ]) && !extra_action spec[:responses][400] = error_response spec[:responses][404] = not_found_response end # All POST, PUT, PATCH should have a request body. if route[:verb].in?([ "POST", "PUT", "PATCH" ]) spec[:requestBody] ||= { content: req_cts.map { |ct| [ ct, (self.model && !extra_action) ? { schema: { "$ref" => "#/components/schemas/#{schema_name}" }, } : {}, ] }.to_h, } end # Add remaining metadata as an extension. spec["x-rrf-metadata"] = if .present? next route[:verb].downcase, spec }.to_h.merge( { parameters: routes.first[:route].required_parts.map { |p| { name: p, in: "path", required: true, schema: { type: "integer" }, } }, }, ), ] }.to_h end |
#openapi_request_content_types ⇒ Object
11 12 13 14 15 16 17 |
# File 'lib/rest_framework/controller/openapi.rb', line 11 def openapi_request_content_types @openapi_request_content_types ||= [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data", ] end |
#openapi_response_content_types ⇒ Object
3 4 5 6 7 8 9 |
# File 'lib/rest_framework/controller/openapi.rb', line 3 def openapi_response_content_types @openapi_response_content_types ||= [ "text/html", self.serialize_to_json ? "application/json" : nil, self.serialize_to_xml ? "application/xml" : nil, ].compact end |
#openapi_schema ⇒ Object
Only for model controllers.
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 |
# File 'lib/rest_framework/controller/openapi.rb', line 160 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[:read_only] 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"] = { class_name: cfg[:reflection].class_name, foreign_key: cfg[:reflection].foreign_key, association_foreign_key: cfg[:reflection].association_foreign_key, association_primary_key: cfg[:reflection].association_primary_key, inverse_of: cfg[:reflection].inverse_of&.name, join_table: cfg[:reflection].join_table, }.compact 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, } @openapi_schema end |
#openapi_schema_name ⇒ Object
Only for model controllers.
220 221 222 |
# File 'lib/rest_framework/controller/openapi.rb', line 220 def openapi_schema_name @openapi_schema_name ||= self.name.chomp("Controller").gsub("::", ".") end |
#rrf_finalize ⇒ Object
Define any behavior to execute at the end of controller definition. :nocov:
139 140 141 142 143 144 145 146 147 148 149 |
# File 'lib/rest_framework/controller.rb', line 139 def rrf_finalize if RESTFramework.config.freeze_config self::RRF_BASE_CONFIG.keys.each { |k| v = self.send(k) v.freeze if v.is_a?(Hash) || v.is_a?(Array) } end self.setup_delegation if self.model # self.setup_channel if self.model end |
#setup_delegation ⇒ Object
Only for model controllers.
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
# File 'lib/rest_framework/controller.rb', line 362 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.model.respond_to?(action) self.define_method(action) do if self.model.method(action).parameters.last&.first == :keyrest render(api: self.model.send(action, **params)) else render(api: self.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.model.method_defined?(action) self.define_method(action) do record = self.get_record if record.method(action).parameters.last&.first == :keyrest render(api: record.send(action, **params)) else render(api: record.send(action)) end end end end |