Module: BarkestCore::AssociationWithDefaults

Defined in:
lib/barkest_core/concerns/association_with_defaults.rb

Overview

This module allows you to define defaults for a model’s associations.

While models can be setup with static defaults, this allows you to provide dynamic defaults. You must define the association_defaults method within the association block for it to work though. This method should process the attributes in whatever way it needs. In the example below, we would actually want to look for org and access attributes before overriding the org_id and access_id attributes.

This method will override the new, build, create, and create! methods of the association to ensure the dynamic defaults are processed properly.

class User
  ...
  has_many :accesses, ->{ extending BarkestCore::AssociationWithDefaults } do
    def association_defaults(attributes = {})
      {
        org_id: proxy_association.owner.current_organization.id,
        access_id: Access.default.id
      }.merge(attributes || {})
    end
  end
  ...
end

Instance Method Summary collapse

Instance Method Details

#build(*args) ⇒ Object



39
40
41
42
43
# File 'lib/barkest_core/concerns/association_with_defaults.rb', line 39

def build(*args)
  args << {} if args.blank?
  args = args.map { |a| a.is_a?(Hash) ? association_defaults(a) : a }
  super(*args)
end

#create(attributes = {}) ⇒ Object



45
46
47
# File 'lib/barkest_core/concerns/association_with_defaults.rb', line 45

def create(attributes = {})
  super association_defaults(attributes)
end

#create!(attributes = {}) ⇒ Object



49
50
51
# File 'lib/barkest_core/concerns/association_with_defaults.rb', line 49

def create!(attributes = {})
  super association_defaults(attributes)
end

#new(attributes = {}) ⇒ Object

def association_defaults(attributes = {})

 attributes[:some_value] ||= some_default
 attributes
end


35
36
37
# File 'lib/barkest_core/concerns/association_with_defaults.rb', line 35

def new(attributes = {})
  super association_defaults(attributes)
end