Module: Gorillib::Collection::ItemsBelongTo

Extended by:
Gorillib::Concern
Includes:
CommonAttrs
Defined in:
lib/gorillib/collection/model_collection.rb

Overview

Examples:

class Smurf
  include Gorillib::Model
end

# Sets the 'village' attribute on each item it receives to the object
# this collection belongs to.
class SmurfCollection < ModelCollection
  include Gorillib::Collection::ItemsBelongTo
  self.item_type        = Smurf
  self.parentage_method = :village
end

# SmurfVillage makes sure its SmurfCollection knows that it `belongs_to` the village
class SmurfVillage
  include Gorillib::Model
  field :name,   Symbol
  field :smurfs, SmurfCollection, default: ->{ SmurfCollection.new(belongs_to: self) }
end

# all the normal stuff works as you'd expect
smurf_town = SmurfVillage.new('smurf_town')   # #<SmurfVillage name=smurf_town>
smurf_town.smurfs                             # c{ }
smurf_town.smurfs.belongs_to                  # #<SmurfVillage name=smurf_town>

# when a new smurf moves to town, it knows what village it belongs_to
smurf_town.smurfs.receive_item(:novel_smurf, smurfiness: 10)
# => #<Smurf name=:novel_smurf smurfiness=10 village=#<SmurfVillage name=smurf_town>>

Instance Method Summary collapse

Methods included from Gorillib::Concern

append_features, extended, included

Methods included from CommonAttrs

#receive_item, #update_or_add

Instance Method Details

#add(item, *args) ⇒ Object



149
150
151
152
# File 'lib/gorillib/collection/model_collection.rb', line 149

def add(item, *args)
  item.send("#{parentage_method}=", belongs_to)
  super
end

#initialize(*args) ⇒ Object

add this collection's belongs_to to the common attrs, so that a newly-created object knows its parentage from birth.



144
145
146
147
# File 'lib/gorillib/collection/model_collection.rb', line 144

def initialize(*args)
  super
  @common_attrs = self.common_attrs.merge(parentage_method => self.belongs_to)
end