Module: Cistern::Associations

Defined in:
lib/cistern/associations.rb

Instance Method Summary collapse

Instance Method Details

#associationsHash{Symbol=>Array}

Lists the associations defined on the resource

Returns:

  • (Hash{Symbol=>Array})

    mapping of association type to name



6
7
8
# File 'lib/cistern/associations.rb', line 6

def associations
  @associations ||= Hash.new { |h,k| h[k] = [] }
end

#belongs_to(name, block) ⇒ Cistern::Model

Define an assocation that references a model.

Examples:

class Firm < Law::Model
  identity :registration_id
  belongs_to :leader, -> { cistern.employees.get(:ceo) }
 end

Parameters:

  • name (Symbol)

    name of association and corresponding reader.

  • scope (Proc)

    returning a Model that is evaluated within the context of the model.

Returns:



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/cistern/associations.rb', line 54

def belongs_to(name, block)
  name_sym = name.to_sym

  reader_method = name
  writer_method = "#{name}="

  attribute name_sym

  define_method reader_method do
    model = instance_exec(&block)
    attributes[name_sym] = model.attributes
    model
  end

  define_method writer_method do |model|
    data = model.respond_to?(:attributes) ? model.attributes : model
    attributes[name_sym] = data
    model
  end

  associations[:belongs_to] << name_sym
end

#has_many(name, scope) ⇒ Cistern::Collection

Define an assocation that references a collection.

Examples:

class Firm < Law::Model
  identity :registration_id
  has_many :lawyers, -> { cistern.associates(firm_id: identity) }
 end

Parameters:

  • name (Symbol)

    name of association and corresponding reader and writer.

  • scope (Proc)

    returning Collection instance to load models into. #scope is evaluated within the context of the model.

Returns:



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/cistern/associations.rb', line 20

def has_many(name, scope)
  name_sym = name.to_sym

  reader_method = name
  writer_method = "#{name}="

  attribute name, type: :array

  define_method reader_method do
    collection = instance_exec(&scope)
    records = attributes[name_sym] || []

    collection.load(records) if records.any?
    collection
  end

  define_method writer_method do |models|
    attributes[name] = Array(models).map do |model|
      model.respond_to?(:attributes) ? model.attributes : model
    end
  end

  associations[:has_many] << name_sym
end