Module: RESTFramework::Utils
- Defined in:
- lib/rest_framework/utils.rb
Constant Summary collapse
- HTTP_VERB_ORDERING =
%w(GET POST PUT PATCH DELETE OPTIONS HEAD)
Class Method Summary collapse
-
.comparable_path(path) ⇒ Object
Normalize a path pattern by replacing URL params with generic placeholder, and removing the ‘(.:format)` at the 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.
-
.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.
-
.get_skipped_builtin_actions(controller_class) ⇒ Object
Get actions which should be skipped for a given controller.
-
.id_field_for(field, reflection) ⇒ Object
Get a field’s id/ids variation.
-
.inflect(s, acronyms = nil) ⇒ Object
Custom inflector for RESTful controllers.
-
.parse_extra_actions(extra_actions, controller: nil) ⇒ Object
Convert ‘extra_actions` hash to a consistent format: `methods:, kwargs:`.
-
.parse_fields_hash(h, model, exclude_associations:, action_text:, active_storage:) ⇒ Object
Parse fields hashes.
-
.sub_fields_for(ref) ⇒ Object
Get the sub-fields that may be serialized and filtered/ordered for a reflection.
-
.wrap_ams(s) ⇒ Object
Wrap a serializer with an adapter if it is an ActiveModel::Serializer.
Class Method Details
.comparable_path(path) ⇒ Object
Normalize a path pattern by replacing URL params with generic placeholder, and removing the ‘(.:format)` at the end.
76 77 78 |
# File 'lib/rest_framework/utils.rb', line 76 def self.comparable_path(path) return path.gsub("(.:format)", "").gsub(/:[0-9A-Za-z_-]+/, ":x") 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.
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 |
# File 'lib/rest_framework/utils.rb', line 181 def self.fields_for(model, exclude_associations:, action_text:, active_storage:) foreign_keys = model.reflect_on_all_associations(:belongs_to).map(&:foreign_key) base_fields = model.column_names.reject { |c| c.in?(foreign_keys) } 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 return base_fields + associations + atf + asf end |
.get_request_route(application_routes, request) ⇒ Object
Get the first route pattern which matches the given request.
70 71 72 |
# File 'lib/rest_framework/utils.rb', line 70 def self.get_request_route(application_routes, request) 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.
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 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/rest_framework/utils.rb', line 81 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. return 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. [request.params[:controller] == c ? 0 : 1, c] }.to_h end |
.get_skipped_builtin_actions(controller_class) ⇒ Object
Get actions which should be skipped for a given controller.
61 62 63 64 65 66 67 |
# File 'lib/rest_framework/utils.rb', line 61 def self.get_skipped_builtin_actions(controller_class) return ( RESTFramework::BUILTIN_ACTIONS.keys + RESTFramework::BUILTIN_MEMBER_ACTIONS.keys ).reject do |action| controller_class.method_defined?(action) end end |
.id_field_for(field, reflection) ⇒ Object
Get a field’s id/ids variation.
237 238 239 240 241 242 243 244 245 246 247 |
# File 'lib/rest_framework/utils.rb', line 237 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 return nil end |
.inflect(s, acronyms = nil) ⇒ Object
Custom inflector for RESTful controllers.
147 148 149 150 151 152 153 |
# File 'lib/rest_framework/utils.rb', line 147 def self.inflect(s, acronyms=nil) acronyms&.each do |acronym| s = s.gsub(/\b#{acronym}\b/i, acronym) end return s end |
.parse_extra_actions(extra_actions, controller: nil) ⇒ Object
Convert ‘extra_actions` hash to a consistent format: `methods:, kwargs:`.
If a controller is provided, labels will be added to any metadata fields.
7 8 9 10 11 12 13 14 15 16 17 18 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 |
# File 'lib/rest_framework/utils.rb', line 7 def self.parse_extra_actions(extra_actions, controller: nil) return (extra_actions || {}).map { |k, v| path = k # Convert structure to path/methods/kwargs. if v.is_a?(Hash) # Allow kwargs to be used to define path differently from the key. # Symbolize keys (which also makes a copy so we don't mutate the original). v = v.symbolize_keys methods = v.delete(:methods) if v.key?(:method) methods = v.delete(:method) end # Add label to metadata fields, if any exist. = v[:metadata] if controller && &.key?(:fields) [:fields] = [:fields].map { |f| [f, {}] }.to_h if [:fields].is_a?(Array) [:fields]&.each do |field, cfg| cfg[:label] = controller.label_for(field) unless cfg[:label] end end # Override path if it's provided. if v.key?(:path) path = v.delete(:path) end # Pass any further kwargs to the underlying Rails interface. kwargs = v.presence elsif v.is_a?(Array) && v.length == 1 methods = v[0] else methods = v end # Insert action label if it's not provided. if controller [:label] ||= controller.label_for(k) end next [ k, { path: path, methods: methods, kwargs: kwargs, }.compact, ] }.to_h end |
.parse_fields_hash(h, model, exclude_associations:, action_text:, active_storage:) ⇒ Object
Parse fields hashes.
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/utils.rb', line 156 def self.parse_fields_hash(h, model, exclude_associations:, action_text:, active_storage:) parsed_fields = h[:only] || ( model ? self.fields_for( model, exclude_associations: exclude_associations, action_text: action_text, active_storage: active_storage, ) : [] ) parsed_fields += h[:include].map(&:to_s) if h[:include] parsed_fields -= h[:exclude].map(&:to_s) if h[:exclude] parsed_fields -= h[:except].map(&:to_s) if h[:except] # Warn for any unknown keys. (h.keys - [:only, :except, :include, :exclude]).each do |k| Rails.logger.warn("RRF: Unknown key in fields hash: #{k}") end # We should always return strings, not symbols. return parsed_fields.map(&:to_s) end |
.sub_fields_for(ref) ⇒ Object
Get the sub-fields that may be serialized and filtered/ordered for a reflection.
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
# File 'lib/rest_framework/utils.rb', line 215 def self.sub_fields_for(ref) if !ref.polymorphic? && model = ref.klass sub_fields = [model.primary_key].flatten.compact label_fields = RESTFramework.config.label_fields # Preferrably find a database column to use as label. if match = label_fields.find { |f| f.in?(model.column_names) } return sub_fields + [match] end # Otherwise, find a method. if match = label_fields.find { |f| model.method_defined?(f) } return sub_fields + [match] end return sub_fields end return ["id", "name"] end |
.wrap_ams(s) ⇒ Object
Wrap a serializer with an adapter if it is an ActiveModel::Serializer.
250 251 252 253 254 255 256 |
# File 'lib/rest_framework/utils.rb', line 250 def self.wrap_ams(s) if defined?(ActiveModel::Serializer) && (s < ActiveModel::Serializer) return RESTFramework::ActiveModelSerializerAdapterFactory.for(s) end return s end |