Module: Sumaki::Model::Associations::ClassMethods

Defined in:
lib/sumaki/model/associations.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#_sumaki_association_reflectionsObject



134
135
136
# File 'lib/sumaki/model/associations.rb', line 134

def _sumaki_association_reflections
  @_sumaki_association_reflections ||= {}
end

#repeated(name, class_name: nil) ⇒ Object

Access to the repeated sub objects

class Company
  include Sumaki::Model
  repeated :member

  class Member
    include Sumaki::Model
  end
end

data = {
  name: 'The Ronaldo Vampire Hunter Agency',
  member: [
    { name: 'Ronaldo' },
    { name: 'Draluc' },
    { name: 'John' }
  ]
}
company = Company.new(data)
company.member[2].class #=> Company::Member

Sub object can also be created.

company = Company.new({})
company.member.build(name: 'John')
company.member[0].name #=> 'John'

Options

:class_name

Specify the name of the class to wrap. Use this if the name of the class to wrap is not inferred from the nested field names.



129
130
131
132
# File 'lib/sumaki/model/associations.rb', line 129

def repeated(name, class_name: nil)
  reflection = Reflection::Repeated.new(self, name, class_name: class_name)
  AccessorAdder::Repeated.add(_sumaki_methods_module, _sumaki_association_reflections, reflection)
end

#singular(name, class_name: nil) ⇒ Object

Access to the sub object.

class Book
  include Sumaki::Model
  singular :company

  class Company
    include Sumaki::Model
  end
end

data = {
  title: 'The Ronaldo Chronicles',
  company: {
    name: 'Autumn Books',
  }
}
book = Book.new(data)
book.company.class #=> Book::Company

Sub object can also be created.

book = Book.new({})
book.build_company(name: 'Autumn Books')
book.company #=> #<Book::Company:0x000073a618e31e80 name: "Autumn Books">

Options

:class_name

Specify the name of the class to wrap. Use this if the name of the class to wrap is not inferred from the nested field names.



91
92
93
94
# File 'lib/sumaki/model/associations.rb', line 91

def singular(name, class_name: nil)
  reflection = Reflection::Singular.new(self, name, class_name: class_name)
  AccessorAdder::Singular.add(_sumaki_methods_module, _sumaki_association_reflections, reflection)
end