Module: RESTFramework::Utils
- Defined in:
- lib/rest_framework/utils.rb
Constant Summary collapse
- HTTP_VERB_ORDERING =
%w[GET POST PUT PATCH DELETE OPTIONS HEAD]
- FIELD_SPEC_KEYS =
A
fieldsspec's structural (non-config) keys, i.e. those that shape set membership. [ :only, :except, :include, :exclude, :config ].freeze
Class Method Summary collapse
-
.association_fields_for(ref) ⇒ Object
Get the association's fields that may be serialized and filtered/ordered for a reflection.
-
.comparable_path(path) ⇒ Object
Normalize a path pattern by replacing URL params with generic placeholder, and removing the
(.:format)at the end. -
.controller_for_model(current_controller, model) ⇒ Object
Find the REST controller for
modelat the same namespace level ascurrent_controller, e.g. -
.fields_for(model, exclude_associations:, action_text:, active_storage:) ⇒ Object
Get the fields for a given model, including not just columns (which includes foreign keys), but also associations.
-
.get_request_route(application_routes, request) ⇒ Object
Get the first route pattern which matches the given request.
-
.get_routes(application_routes, request, current_route: nil) ⇒ Object
Show routes under a controller action; used for the browsable API.
-
.id_field_for(field, reflection) ⇒ Object
Get a field's id/ids variation.
-
.inflect(s, acronyms = nil) ⇒ Object
Custom inflector for RESTful controllers.
-
.normalize_field_spec(spec) ⇒ Object
Normalize a field spec — an Array, a Hash, or nil — into a canonical
{only:, include:, exclude:, config:}Hash containing only the keys that are present. -
.parse_fields_hash(h, model, exclude_associations:, action_text:, active_storage:) ⇒ Object
Resolve a top-level
fieldshash to an ordered array of string field names, using the model's default fields as the base. -
.resolve_field_names(spec, base) ⇒ Object
Resolve a field spec (Array | Hash | nil) to an ordered array of string field names: start from
baseunlessonly:replaces it, then applyinclude:. -
.serialize_polymorphic(target, type, fields = nil) ⇒ Object
Serialize a polymorphic association's target as
{<pk> => id, "type" => type}, plus a label entry when the target responds to one of the configuredlabel_fields. -
.wrap_ams(s) ⇒ Object
Wrap a serializer with an adapter if it is an ActiveModel::Serializer.
Class Method Details
.association_fields_for(ref) ⇒ Object
Get the association's fields that may be serialized and filtered/ordered for a reflection.
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
# File 'lib/rest_framework/utils.rb', line 187 def self.association_fields_for(ref) if !ref.polymorphic? && model = ref.klass fields = [ model.primary_key ].flatten.compact label_fields = RESTFramework.config.label_fields # Preferably find a database column to use as label. if match = label_fields.find { |f| f.in?(model.column_names) } return fields + [ match ] end # Otherwise, find a method. if match = label_fields.find { |f| model.method_defined?(f) } return fields + [ match ] end return fields end # A polymorphic association has no single target class, so we can't resolve a label column ahead # of time. The id and type together identify the record; a per-record label is added at # serialization time when the target has one (see `serialize_polymorphic`). [ "id", "type" ] end |
.comparable_path(path) ⇒ Object
Normalize a path pattern by replacing URL params with generic placeholder, and removing the
(.:format) at the end.
18 19 20 |
# File 'lib/rest_framework/utils.rb', line 18 def self.comparable_path(path) path.gsub("(.:format)", "").gsub(/:[0-9A-Za-z_-]+/, ":x") end |
.controller_for_model(current_controller, model) ⇒ Object
Find the REST controller for model at the same namespace level as current_controller, e.g.
Api::Demo::MoviesController + Genre => Api::Demo::GenresController, or nil if none. The
model match guards against trusting a same-named controller for a different model.
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/rest_framework/utils.rb', line 253 def self.controller_for_model(current_controller, model) return nil unless model && (base_name = current_controller.name) namespace = base_name.deconstantize model_name = model.model_name # Plural for a collection controller, singular for a singular-resource one. [ model_name.plural, model_name.singular ].each do |name| candidate_name = "#{name.camelize}Controller" candidate_name = "#{namespace}::#{candidate_name}" if namespace.present? candidate = candidate_name.safe_constantize next unless candidate.is_a?(Class) && candidate.include?(RESTFramework::Controller) next unless candidate.model == model return candidate end nil end |
.fields_for(model, exclude_associations:, action_text:, active_storage:) ⇒ Object
Get the fields for a given model, including not just columns (which includes foreign keys), but also associations. Note that we always return an array of strings, not symbols.
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 |
# File 'lib/rest_framework/utils.rb', line 147 def self.fields_for(model, exclude_associations:, action_text:, active_storage:) belongs_to = model.reflect_on_all_associations(:belongs_to) # A polymorphic `belongs_to` is backed by both a foreign key and a `*_type` column; the # association represents both, so drop them from the plain column fields (as we already do for # every foreign key). excluded_columns = belongs_to.map(&:foreign_key) excluded_columns += belongs_to.select(&:polymorphic?).map(&:foreign_type) base_fields = model.column_names.reject { |c| c.in?(excluded_columns) } return base_fields if exclude_associations # ActionText Integration: Determine the normalized field names for action text attributes. atf = action_text ? model.reflect_on_all_associations(:has_one).collect(&:name).select { |n| n.to_s.start_with?("rich_text_") }.map { |n| n.to_s.delete_prefix("rich_text_") } : [] # ActiveStorage Integration: Determine the normalized field names for active storage attributes. asf = active_storage ? model..keys : [] # Associations: associations = model.reflections.map { |association, ref| # Ignore associations for which we have custom integrations. if ref.class_name.in?(%w[ActionText::RichText ActiveStorage::Attachment ActiveStorage::Blob]) next nil end if ref.collection? && RESTFramework.config.large_reverse_association_tables&.include?( ref.table_name, ) next nil end next association }.compact base_fields + associations + atf + asf end |
.get_request_route(application_routes, request) ⇒ Object
Get the first route pattern which matches the given request.
5 6 7 8 9 10 11 12 13 14 |
# File 'lib/rest_framework/utils.rb', line 5 def self.get_request_route(application_routes, request) # Prefer the route already resolved by the router to avoid an expensive `recognize` call. This # is also required for Rails 8.1+ where OPTIONS routes are non-anchored, causing `path_info` to # be modified during dispatch, which makes `recognize` fail from inside the controller action. if route = request.env["action_dispatch.route"] return route end application_routes.router.recognize(request) { |route, _| return route } end |
.get_routes(application_routes, request, current_route: nil) ⇒ Object
Show routes under a controller action; used for the browsable API.
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 |
# File 'lib/rest_framework/utils.rb', line 23 def self.get_routes(application_routes, request, current_route: nil) current_route ||= self.get_request_route(application_routes, request) current_path = current_route.path.spec.to_s.gsub("(.:format)", "") current_path = "" if current_path == "/" current_levels = current_path.count("/") current_comparable_path = %r{^#{Regexp.quote(self.comparable_path(current_path))}(/|$)} # Get current route path parameters. path_params = current_route.required_parts.map { |n| request.path_parameters[n] } # Return routes that match our current route subdomain/pattern, grouped by controller. We # precompute certain properties of the route for performance. application_routes.routes.select { |r| # We `select` first to avoid unnecessarily calculating metadata for routes we don't even want # to show. (r.defaults[:subdomain].blank? || r.defaults[:subdomain] == request.subdomain) && current_comparable_path.match?(self.comparable_path(r.path.spec.to_s)) && r.defaults[:controller].present? && r.defaults[:action].present? }.map { |r| path = r.path.spec.to_s.gsub("(.:format)", "") # Starts at the number of levels in current path, and removes the `(.:format)` at the end. relative_path = path.split("/")[current_levels..]&.join("/").presence || "/" # This path is what would need to be concatenated onto the current path to get to the # destination path. concat_path = relative_path.gsub(/^[^\/]*/, "").presence || "/" levels = path.count("/") matches_path = current_path == path matches_params = r.required_parts.length == current_route.required_parts.length { route: r, verb: r.verb, path: path, path_with_params: r.format( r.required_parts.each_with_index.map { |p, i| [ p, path_params[i] ] }.to_h, ), relative_path: relative_path, concat_path: concat_path, controller: r.defaults[:controller].presence, action: r.defaults[:action].presence, matches_path: matches_path, matches_params: matches_params, # The following options are only used in subsequent processing in this method. _levels: levels, } }.sort_by { |r| [ # Sort by levels first, so routes matching closely with current request show first. r[:_levels], # Then match by path, but manually sort ':' to the end using knowledge that Ruby sorts the # pipe character '|' after alphanumerics. r[:path].tr(":", "|"), # Finally, match by HTTP verb. HTTP_VERB_ORDERING.index(r[:verb]) || 99, ] }.group_by { |r| r[:controller] }.sort_by { |c, _r| # Sort the controller groups by current controller first, then alphanumerically. # Note: Use `controller_path` instead of `params[:controller]` to avoid re-raising a # `ActionDispatch::Http::Parameters::ParseError` exception. [ request.controller_class.controller_path == c ? 0 : 1, c ] }.to_h end |
.id_field_for(field, reflection) ⇒ Object
Get a field's id/ids variation.
238 239 240 241 242 243 244 245 246 247 248 |
# File 'lib/rest_framework/utils.rb', line 238 def self.id_field_for(field, reflection) if reflection.collection? return "#{field.singularize}_ids" elsif reflection.belongs_to? # The id field for belongs_to is always the foreign key column name, even if the # association is named differently. return reflection.foreign_key end nil end |
.inflect(s, acronyms = nil) ⇒ Object
Custom inflector for RESTful controllers.
91 92 93 94 95 96 97 |
# File 'lib/rest_framework/utils.rb', line 91 def self.inflect(s, acronyms = nil) acronyms&.each do |acronym| s = s.gsub(/\b#{acronym}\b/i, acronym) end s end |
.normalize_field_spec(spec) ⇒ Object
Normalize a field spec — an Array, a Hash, or nil — into a canonical
{only:, include:, exclude:, config:} Hash containing only the keys that are present. A plain
Array is sugar for only:. except: is an alias of exclude:; the two are merged.
105 106 107 108 109 110 111 |
# File 'lib/rest_framework/utils.rb', line 105 def self.normalize_field_spec(spec) return {} if spec.nil? return { only: spec } unless spec.is_a?(Hash) exclude = (Array(spec[:exclude]) + Array(spec[:except])).presence { only: spec[:only], include: spec[:include], exclude: exclude, config: spec[:config] }.compact end |
.parse_fields_hash(h, model, exclude_associations:, action_text:, active_storage:) ⇒ Object
Resolve a top-level fields hash to an ordered array of string field names, using the model's
default fields as the base. The config: key carries per-field configuration and is ignored for
membership.
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
# File 'lib/rest_framework/utils.rb', line 129 def self.parse_fields_hash(h, model, exclude_associations:, action_text:, active_storage:) base = model ? self.fields_for( model, exclude_associations: exclude_associations, action_text: action_text, active_storage: active_storage, ) : [] # Warn for any unknown keys. (h.keys.map(&:to_sym) - FIELD_SPEC_KEYS).each do |k| Rails.logger.warn("RRF: Unknown key in fields hash: #{k}.") end self.resolve_field_names(h, base) end |
.resolve_field_names(spec, base) ⇒ Object
Resolve a field spec (Array | Hash | nil) to an ordered array of string field names: start from
base unless only: replaces it, then apply include:. Any field named in config: is
implicitly part of the set (so a configured field never needs to be listed twice). exclude: is
applied last, so it can still drop a field that config:/include: would otherwise add.
117 118 119 120 121 122 123 124 |
# File 'lib/rest_framework/utils.rb', line 117 def self.resolve_field_names(spec, base) spec = self.normalize_field_spec(spec) names = (spec[:only] || base).map(&:to_s) names += spec[:include].map(&:to_s) if spec[:include] names |= spec[:config].keys.map(&:to_s) if spec[:config] names -= spec[:exclude].map(&:to_s) if spec[:exclude] names end |
.serialize_polymorphic(target, type, fields = nil) ⇒ Object
Serialize a polymorphic association's target as {<pk> => id, "type" => type}, plus a label
entry when the target responds to one of the configured label_fields. The type comes from the
parent's *_type column, so it matches exactly what is stored (and what a reverse lookup uses).
fields are the association's configured fields. id/type are always emitted above; any
other field is resolved against the target and included when it responds to it, so a field
absent on a target class (e.g. price on a Genre) is omitted rather than serialized as nil.
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/rest_framework/utils.rb', line 218 def self.serialize_polymorphic(target, type, fields = nil) result = {} Array(target.class.primary_key).each { |pk| result[pk] = target.public_send(pk) } result["type"] = type if label = RESTFramework.config.label_fields.find { |f| target.respond_to?(f) } result[label.to_s] = target.public_send(label) end Array(fields).each do |f| f = f.to_s next if f.in?(%w[id type]) || result.key?(f) result[f] = target.public_send(f) if target.respond_to?(f) end result end |
.wrap_ams(s) ⇒ Object
Wrap a serializer with an adapter if it is an ActiveModel::Serializer.
275 276 277 278 279 280 281 |
# File 'lib/rest_framework/utils.rb', line 275 def self.wrap_ams(s) if defined?(ActiveModel::Serializer) && (s < ActiveModel::Serializer) return RESTFramework::ActiveModelSerializerAdapterFactory.for(s) end s end |