module Gorillib::Collection::ItemsBelongTo

@example

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>>

Public Class Methods

new(*args) click to toggle source

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

Calls superclass method Gorillib::Collection::CommonAttrs::new
# 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

Public Instance Methods

add(item, *args) click to toggle source
Calls superclass method
# File lib/gorillib/collection/model_collection.rb, line 149
def add(item, *args)
  item.send("#{parentage_method}=", belongs_to)
  super
end