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



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

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.



122
123
124
# File 'lib/gecko/helpers/association_helper.rb', line 122

def association_name
  @association_name
end

#parentObject (readonly)

Returns the value of attribute parent.



122
123
124
# File 'lib/gecko/helpers/association_helper.rb', line 122

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


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

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



164
165
166
# File 'lib/gecko/helpers/association_helper.rb', line 164

def embed_records?
  !!@embedded
end