Class: Spree::ModelExtensions

Inherits:
Object
  • Object
show all
Defined in:
lib/spree/core/model_extensions.rb

Overview

Adds an extension's own methods, associations, scopes and validations to core models without a decorator.

An extension writes an ordinary concern and registers it against the model by name. Spree includes it, so the model's own methods still win: an extension adds to a model, it never replaces what the model does. A concern that would shadow a method, attribute or association the model already has is refused at boot, naming both, where a decorator would overwrite it quietly.

Registrations are kept as names and included again each time code is reloaded, so development reloading keeps them.

Examples:

Spree.model_extensions.add('Spree::Product', 'MyExtension::ProductWarranty')
Spree.model_extensions.add(:customer, 'MyExtension::CustomerWarranties')

Defined Under Namespace

Classes: Conflict

Constant Summary collapse

USER_MODELS =

The configured customer and admin user classes, which an extension cannot know by name.

{ customer: -> { Spree.customer_class }, admin_user: -> { Spree.admin_user_class } }.freeze

Instance Method Summary collapse

Constructor Details

#initialize ⇒ ModelExtensions

Returns a new instance of ModelExtensions.



24
25
26
27
# File 'lib/spree/core/model_extensions.rb', line 24

def initialize
  @extensions = Hash.new { |hash, key| hash[key] = [] }
  @prepared = false
end

Instance Method Details

#add(model, extension) ⇒ void

This method returns an undefined value.

Parameters:

  • model (String, Symbol) —

    the model's class name, e.g. 'Spree::Product', or :customer / :admin_user

  • extension (String, Module) —

    the concern to include

Raises:

  • (ArgumentError) —

    for a symbol other than :customer and :admin_user

  • (Conflict) —

    when the concern would shadow something the model already has



34
35
36
37
38
39
# File 'lib/spree/core/model_extensions.rb', line 34

def add(model, extension)
  key = key_for(model)
  name = extension.is_a?(Module) ? extension.name : extension.to_s
  @extensions[key] |= [name]
  apply_to(key, name) if @prepared
end

#apply ⇒ void

This method returns an undefined value.

Includes every registered concern. Spree runs it each time code is loaded; a registration made after that is included straight away.



51
52
53
54
# File 'lib/spree/core/model_extensions.rb', line 51

def apply
  @prepared = true
  @extensions.each { |key, names| names.each { |name| apply_to(key, name) } }
end

#for(model) ⇒ Array<String>

Returns the concerns registered for the model.

Parameters:

  • model (String, Symbol)

Returns:

  • (Array<String>) —

    the concerns registered for the model



43
44
45
# File 'lib/spree/core/model_extensions.rb', line 43

def for(model)
  @extensions.fetch(key_for(model), []).dup
end