Class: Gecko::Helpers::CollectionProxy

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/gecko/helpers/association_helper.rb

Overview

Provides a convenient wrapper for a collection of child records. Exposes both an Enumerable interface as well as the ability to create new child records

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent:, association_name:, class_name:, target:, embedded:) ⇒ Hash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Setup the child collection proxy



127
128
129
130
131
132
133
# File 'lib/gecko/helpers/association_helper.rb', line 127

def initialize(parent:, association_name:, class_name:, target:, embedded:)
  @parent           = parent
  @target           = target
  @embedded         = embedded
  @class_name       = class_name
  @association_name = association_name
end

Instance Attribute Details

#association_nameObject (readonly)

Returns the value of attribute association_name.



120
121
122
# File 'lib/gecko/helpers/association_helper.rb', line 120

def association_name
  @association_name
end

#parentObject (readonly)

Returns the value of attribute parent.



120
121
122
# File 'lib/gecko/helpers/association_helper.rb', line 120

def parent
  @parent
end

Instance Method Details

#build(attributes) ⇒ Gecko::Record::Base

Build a new child object inside the collection

Examples:

item = order.order_line_items.build(variant_id: 1234, quantiy: 12.5, price: 13.45)
order.order_line_items.include?(item) #=> true

Parameters:

  • attributes (#to_hash)

    for the child record

Returns:



146
147
148
149
150
151
152
153
154
155
# File 'lib/gecko/helpers/association_helper.rb', line 146

def build(attributes)
  if @parent.persisted?
    parent_foreign_key = @parent.class.demodulized_name.foreign_key.to_sym
    attributes[parent_foreign_key] = @parent.id
  end

  record = client.adapter_for(@class_name).build(attributes)
  @target << record
  record
end

#embed_records?Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Should this collection of records be serialized inside it’s parent object

Returns:

  • (Boolean)


162
163
164
# File 'lib/gecko/helpers/association_helper.rb', line 162

def embed_records?
  !!@embedded
end