Class: Spree::Base
- Inherits:
-
ApplicationRecord
- Object
- ApplicationRecord
- Spree::Base
- Includes:
- HasIsoGeography, HasNumber, IntegrationsConcern, PreferenceSchema, Preferences::Preferable, PrefixedId, Publishable, RansackableAttributes, SignedIdAttachments, TranslatableResourceScopes, TypedAssociations, ValidatesStoreUniqueness
- Defined in:
- app/models/spree/base.rb
Direct Known Subclasses
Constant Summary
Constants included from HasIsoGeography
Constants included from HasNumber
Constants included from PrefixedId
Constants included from Publishable
Publishable::LIFECYCLE_ACTIONS
Constants included from RansackableAttributes
RansackableAttributes::RESTRICTED_AUDIENCES
Constants included from Preferences::Preferable
Preferences::Preferable::BOOLEAN_TYPE, Preferences::Preferable::INTEGER_TYPE, Preferences::Preferable::STRING_TYPE
Class Method Summary collapse
-
.api_type ⇒ Object
Public-API shorthand for this class, used as the
typevalue on the wire (e.g."currency"forSpree::Promotion::Rules::Currency,"flat_rate"forSpree::Calculator::FlatRate). -
.api_type_for(type) ⇒ String
.api_typefor an STItypecolumn value, without instantiating the subclass — use this in serializers instead ofrecord.class.api_type, which reports the loaded class and so returns the base type for a record read through the parent (a plainSpree::Exportrow, a factory that setstypeas an attribute, a query on the base relation). -
.api_type_registry ⇒ Array<Class>
The subclasses a typed family accepts —
registered_subclassesfor the preference-schema families,available_typesfor exports and imports. -
.api_type_resolver(attribute) ⇒ Proc?
How a filter on one of this model's columns turns the short name a client sends (
purchase_order) into the class name the column stores, or nil when the column does not store class names. -
.class_name_for_api_type(api_type) ⇒ String?
Inverse of Base.api_type_for: the STI
typecolumn value for a wire shorthand, or nil when no registered subclass answers to it. -
.for_store(store) ⇒ ActiveRecord::Relation
The store's own rows of this model, through the association named after it.
- .json_api_columns ⇒ Object
- .json_api_permitted_attributes ⇒ Object
-
.json_api_type ⇒ Object
Backwards-compatible alias for
.api_type. -
.polymorphic_api_type(type) ⇒ String?
Shorthand for a polymorphic
*_typecolumn (owner_type,viewable_type, …), where the value names an arbitrary model rather than a subclass of the serialized one — soapi_type_for's registry lookup does not apply. -
.polymorphic_prefixed_id(type, id) ⇒ String?
Prefixed id for a polymorphic reference, encoded from the columns without loading the row.
-
.polymorphic_type_for(api_type, candidates = nil) ⇒ String?
Inverse of Base.polymorphic_api_type: the class name a polymorphic
*_typecolumn stores for a wire shorthand. -
.ransack_flag(*values) ⇒ Boolean?
Reads the arguments of a two-state ransackable scope — one that answers a question with two named sides ("erased" / "not erased", "outstanding" / "spent") rather than narrowing to a value.
-
.reset_counters_in_bulk(ids, association) ⇒ void
Recomputes a counter cache for many records at once.
- .spree_base_scopes ⇒ Object
- .spree_base_uniqueness_scope ⇒ Object
-
.to_tom_select_json ⇒ Object
deprecated
Deprecated.
Legacy Tom Select helper for the removed Rails admin. No replacement.
Instance Method Summary collapse
-
#api_value_for(attribute, value) ⇒ Object?
What a client reads for
valueheld inattribute— the inverse of Base.api_type_resolver. -
#can_be_deleted? ⇒ Boolean
this can overridden in subclasses to disallow deletion.
- #mysql_adapter? ⇒ Boolean
-
#read_association_in_memory?(name) ⇒ Boolean
Whether to answer from an association's rows rather than a query of its own (a SUM, an EXISTS).
-
#slug_candidates ⇒ Object
Try building a slug based on the following fields in increasing order of specificity.
- #uuid_for_friendly_id ⇒ Object
Methods included from HasNumber
#generate_number, #number_store
Methods included from PrefixedId
#assign_attributes, decode_prefixed_id, #prefixed_id, prefixed_id?, #to_param
Methods included from Publishable
#event_context, #event_payload, #event_payload_for, #event_prefix, #event_serializer_class, #publish_event, #touch
Methods included from IntegrationsConcern
#store_integration, #store_integrations
Methods included from RansackableAttributes
restricted_audience?, scope_type_from_signature, signature_hidden?
Methods included from PreferenceSchema
Methods included from Preferences::Preferable
#assign_preferences, #backfill_default_preferences, #default_preferences, #defined_preferences, #get_preference, #has_preference!, #has_preference?, #money_preference_currency, #preference_choices, #preference_default, #preference_deprecated, #preference_internal, preference_model, #preference_type, #preference_values, #previously_changed_preference_names, restore_value, #set_preference, #stored_preference, #wire_preference_value
Class Method Details
.api_type ⇒ Object
Public-API shorthand for this class, used as the type value on the
wire (e.g. "currency" for Spree::Promotion::Rules::Currency,
"flat_rate" for Spree::Calculator::FlatRate). Defaults to the
demodulized + underscored leaf; override on a subclass when the wire
format should stay stable across class renames.
143 144 145 |
# File 'app/models/spree/base.rb', line 143 def self.api_type to_s.demodulize.underscore end |
.api_type_for(type) ⇒ String
.api_type for an STI type column value, without instantiating the
subclass — use this in serializers instead of record.class.api_type,
which reports the loaded class and so returns the base type for a record
read through the parent (a plain Spree::Export row, a factory that sets
type as an attribute, a query on the base relation).
Resolves against the class's type registry where it has one, so an unrecognized column value (an extension no longer installed) is never constantized — it is shortened the same way instead, never sent as a class name.
166 167 168 169 170 171 |
# File 'app/models/spree/base.rb', line 166 def self.api_type_for(type) return api_type if type.blank? type = type.to_s api_type_registry.find { |klass| klass.to_s == type }&.api_type || type.demodulize.underscore end |
.api_type_registry ⇒ Array<Class>
The subclasses a typed family accepts — registered_subclasses for the
preference-schema families, available_types for exports and imports.
189 190 191 192 193 194 195 196 197 |
# File 'app/models/spree/base.rb', line 189 def self.api_type_registry if subclass_registry registered_subclasses elsif respond_to?(:available_types) Array(available_types) else [] end end |
.api_type_resolver(attribute) ⇒ Proc?
How a filter on one of this model's columns turns the short name a client
sends (purchase_order) into the class name the column stores, or nil
when the column does not store class names. Covers the STI column of a
typed family and polymorphic *_type columns; a model with another such
column overrides this.
207 208 209 210 211 212 213 |
# File 'app/models/spree/base.rb', line 207 def self.api_type_resolver(attribute) if attribute == inheritance_column && api_type_registry.any? ->(api_type) { class_name_for_api_type(api_type) } elsif reflect_on_all_associations(:belongs_to).any? { |reflection| reflection.polymorphic? && reflection.foreign_type == attribute } ->(api_type) { Spree::Base.polymorphic_type_for(api_type) } end end |
.class_name_for_api_type(api_type) ⇒ String?
Inverse of api_type_for: the STI type column value for a wire
shorthand, or nil when no registered subclass answers to it. Lookup is
registry-driven, so a request can never name a class outside the family.
179 180 181 182 183 |
# File 'app/models/spree/base.rb', line 179 def self.class_name_for_api_type(api_type) return nil if api_type.blank? api_type_registry.find { |klass| klass.api_type == api_type.to_s }&.to_s end |
.for_store(store) ⇒ ActiveRecord::Relation
The store's own rows of this model, through the association named after it. A model the store has no association for answers nothing: a tenant boundary that quietly widened to every store's rows is how a cross-store read ships unnoticed. Global reference data (countries, roles) and records reached through a parent are fetched as such, never through here.
57 58 59 60 61 62 63 64 65 |
# File 'app/models/spree/base.rb', line 57 def self.for_store(store) plural_model_name = model_name.plural.gsub(/spree_/, '').to_sym if store.respond_to?(plural_model_name) store.send(plural_model_name) else none end end |
.json_api_columns ⇒ Object
122 123 124 125 126 |
# File 'app/models/spree/base.rb', line 122 def self.json_api_columns # `_type` goes with `_id`: the two halves of a polymorphic reference name # an internal class, which is no more public than the key beside it. column_names.reject { |c| c.match(/_id$|id|_type$|preferences|(.*)password|(.*)token|(.*)api_key|^original_(.*)/) } end |
.json_api_permitted_attributes ⇒ Object
128 129 130 131 132 133 134 135 136 |
# File 'app/models/spree/base.rb', line 128 def self.json_api_permitted_attributes skipped_attributes = %w[id] if included_modules.include?(CollectiveIdea::Acts::NestedSet::Model) skipped_attributes.push('lft', 'rgt', 'depth') end column_names.reject { |c| skipped_attributes.include?(c.to_s) } end |
.json_api_type ⇒ Object
Backwards-compatible alias for .api_type. Delegates so subclass
overrides of api_type are honored.
149 150 151 |
# File 'app/models/spree/base.rb', line 149 def self.json_api_type api_type end |
.polymorphic_api_type(type) ⇒ String?
Shorthand for a polymorphic *_type column (owner_type,
viewable_type, …), where the value names an arbitrary model rather than a
subclass of the serialized one — so api_type_for's registry lookup does
not apply. Demodulizes and underscores the same way api_type does, giving
"Spree::Product" => "product".
The configured customer and admin user classes always answer customer
and admin_user, so a host app's own User class does not change the
contract.
227 228 229 230 231 232 233 234 235 |
# File 'app/models/spree/base.rb', line 227 def self.polymorphic_api_type(type) return nil if type.blank? type = type.to_s return 'customer' if type == Spree.customer_class(constantize: false) return 'admin_user' if type == Spree.admin_user_class(constantize: false) type.demodulize.underscore end |
.polymorphic_prefixed_id(type, id) ⇒ String?
Prefixed id for a polymorphic reference, encoded from the columns without loading the row.
Reads both halves together so a type never appears beside a null id: the
pair names something a client can link to, or neither does. Answers nil for
a model without has_prefix_id — an extension may point a polymorphic
column at one, and one such row must not 500 the whole list.
267 268 269 270 271 |
# File 'app/models/spree/base.rb', line 267 def self.polymorphic_prefixed_id(type, id) return nil if type.blank? || id.blank? type.to_s.safe_constantize.try(:prefixed_id_for, id) end |
.polymorphic_type_for(api_type, candidates = nil) ⇒ String?
Inverse of polymorphic_api_type: the class name a polymorphic *_type
column stores for a wire shorthand. Matches against candidates when the
caller knows what the column may reference (always prefer that); otherwise
against the configured customer and admin user classes, then the
Spree:: model of that name. Never constantizes the input.
246 247 248 249 250 251 252 253 254 |
# File 'app/models/spree/base.rb', line 246 def self.polymorphic_type_for(api_type, candidates = nil) token = api_type.to_s return nil unless token.match?(/\A[a-z][a-z0-9_]*\z/) candidates ||= [Spree.customer_class(constantize: false), Spree.admin_user_class(constantize: false), "Spree::#{token.camelize}"] candidates.map(&:to_s).find { |name| polymorphic_api_type(name) == token } end |
.ransack_flag(*values) ⇒ Boolean?
Reads the arguments of a two-state ransackable scope — one that answers a question with two named sides ("erased" / "not erased", "outstanding" / "spent") rather than narrowing to a value.
Declare such a scope as ->(*values), never ->(value = true). Ransack
calls one of three ways, and only a splat survives all of them:
- a literal boolean
trueinvokes the scope with NO arguments, which means the affirmative side (this is why an empty list reads astrue); - a single value arrives as that value;
- an array predicate is SPLATTED, so a filter offering both sides passes
two arguments and a fixed-arity lambda raises ArgumentError — a 500 on a
request the merchant is entitled to make. Asking for every side is no
constraint at all, which is the
nilbelow.
The scope must also be added to the model's
ransackable_scopes_skip_sanitize_args (super | %w[name]), or Ransack
casts false itself and then declines to apply the scope at all.
323 324 325 326 327 328 329 330 331 332 333 334 |
# File 'app/models/spree/base.rb', line 323 def self.ransack_flag(*values) # No argument is Ransack's shorthand for the affirmative side, not an # absent filter: `q[erased]=true` reaches the scope with nothing at all. return true if values.empty? flags = Array(values).flatten.map { |value| ActiveModel::Type::Boolean.new.cast(value) }.uniq # `size == 1`, not `one?`: the latter counts truthy elements, so a lone # `false` would read as "no side chosen" and drop the filter. return nil unless flags.size == 1 flags.first end |
.reset_counters_in_bulk(ids, association) ⇒ void
This method returns an undefined value.
Recomputes a counter cache for many records at once. Rails'
reset_counters spends two queries per record, which a bulk write pays
for every row it touched; this is one grouped count plus one UPDATE per
distinct value.
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
# File 'app/models/spree/base.rb', line 100 def self.reset_counters_in_bulk(ids, association) ids = Array(ids).compact.uniq return if ids.empty? reflection = reflect_on_association(association) counter = reflection.klass.reflect_on_all_associations(:belongs_to).find do |belongs_to| belongs_to.foreign_key.to_s == reflection.foreign_key.to_s && belongs_to.[:counter_cache] end.counter_cache_column counts = reflection.klass.where(reflection.foreign_key => ids).group(reflection.foreign_key).count ids.group_by { |id| counts.fetch(id, 0) }.each do |count, grouped_ids| unscoped.where(id: grouped_ids).where.not(counter => count).update_all(counter => count) end end |
.spree_base_scopes ⇒ Object
67 68 69 |
# File 'app/models/spree/base.rb', line 67 def self.spree_base_scopes where(nil) end |
.spree_base_uniqueness_scope ⇒ Object
71 72 73 |
# File 'app/models/spree/base.rb', line 71 def self.spree_base_uniqueness_scope ApplicationRecord.try(:spree_base_uniqueness_scope) || [] end |
.to_tom_select_json ⇒ Object
Legacy Tom Select helper for the removed Rails admin. No replacement.
337 338 339 340 341 342 343 344 345 346 |
# File 'app/models/spree/base.rb', line 337 def self.to_tom_select_json Spree::Deprecation.warn('Spree::Base.to_tom_select_json is deprecated and will be removed in Spree 6.3.') pluck(:name, :id).map do |name, id| { id: id, name: name } end.as_json end |
Instance Method Details
#api_value_for(attribute, value) ⇒ Object?
What a client reads for value held in attribute — the inverse of
api_type_resolver. A foreign key becomes the prefixed id of the record
it points at, a column storing a class name becomes its short name, and
anything else is returned unchanged. Override with api_type_resolver
for a column whose stored values need their own mapping.
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
# File 'app/models/spree/base.rb', line 282 def api_value_for(attribute, value) model = self.class attribute = model.attribute_aliases[attribute.to_s] || attribute.to_s reference = model.reflect_on_all_associations(:belongs_to).find { |reflection| reflection.foreign_key.to_s == attribute } if attribute == model.inheritance_column model.base_class.api_type_for(value) elsif reference if reference.polymorphic? Spree::Base.polymorphic_prefixed_id(self[reference.foreign_type], value) else reference.klass.try(:prefixed_id_for, value) end elsif model.api_type_resolver(attribute) Spree::Base.polymorphic_api_type(value) else value end end |
#can_be_deleted? ⇒ Boolean
this can overridden in subclasses to disallow deletion
76 77 78 |
# File 'app/models/spree/base.rb', line 76 def can_be_deleted? true end |
#mysql_adapter? ⇒ Boolean
118 119 120 |
# File 'app/models/spree/base.rb', line 118 def mysql_adapter? Spree.mysql? end |
#read_association_in_memory?(name) ⇒ Boolean
Whether to answer from an association's rows rather than a query of its
own (a SUM, an EXISTS). True when the rows are loaded already, or when
this record came from a list loaded with preload_associations_lazily:
loading them then fetches the rows for the whole list in one query, where
an aggregate would run once per record.
88 89 90 |
# File 'app/models/spree/base.rb', line 88 def read_association_in_memory?(name) association(name).loaded? || lazy_preload_context.present? end |
#slug_candidates ⇒ Object
Try building a slug based on the following fields in increasing order of specificity.
353 354 355 356 357 358 359 360 361 362 363 364 365 |
# File 'app/models/spree/base.rb', line 353 def slug_candidates if defined?(deleted_at) && deleted_at.present? [ ['deleted', :name], ['deleted', :name, :uuid_for_friendly_id] ] else [ [:name], [:name, :uuid_for_friendly_id] ] end end |
#uuid_for_friendly_id ⇒ Object
348 349 350 |
# File 'app/models/spree/base.rb', line 348 def uuid_for_friendly_id SecureRandom.uuid end |