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



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

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.



118
119
120
# File 'lib/gecko/helpers/association_helper.rb', line 118

def association_name
  @association_name
end

#parentObject (readonly)

Returns the value of attribute parent.



118
119
120
# File 'lib/gecko/helpers/association_helper.rb', line 118

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:



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

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)


160
161
162
# File 'lib/gecko/helpers/association_helper.rb', line 160

def embed_records?
  !!@embedded
end