Module: CsvRowModel::Model::Children

Extended by:
ActiveSupport::Concern
Included in:
CsvRowModel::Model
Defined in:
lib/csv_row_model/model/children.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.has_many(relation_name, row_model_class) ⇒ Object

Defines a relationship between a row model (only one relation per model for now).

Parameters:

  • relation_name (Symbol)

    the name of the relation

  • row_model_class (CsvRowModel::Import)

    class of the relation



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/csv_row_model/model/children.rb', line 50

def has_many(relation_name, row_model_class)
  raise "for now, CsvRowModel's has_many may only be called once" if @_has_many_relationships.present?

  relation_name = relation_name.to_sym

  merge_has_many_relationships(relation_name => row_model_class)

  define_method(relation_name) do
    #
    # equal to: @relation_name ||= []
    #
    variable_name = "@#{relation_name}"
    instance_variable_get(variable_name) || instance_variable_set(variable_name, [])
  end
end

Instance Method Details

#append_child(source, options = {}) ⇒ Model

Appends child to the parent and returns it

Returns:

  • (Model)

    return the child if it is valid, otherwise returns nil



17
18
19
20
21
22
23
24
25
26
# File 'lib/csv_row_model/model/children.rb', line 17

def append_child(source, options={})
  self.class.has_many_relationships.each do |relation_name, child_class|
    child_row_model = child_class.new(source, options.reverse_merge(parent: self))
    if child_row_model.valid?
      public_send(relation_name) << child_row_model
      return child_row_model
    end
  end
  nil
end

#child?Boolean

Returns true, if the instance is a child

Returns:

  • (Boolean)

    returns true, if the instance is a child



10
11
12
# File 'lib/csv_row_model/model/children.rb', line 10

def child?
  !!parent
end

#children_public_send(method_name) ⇒ Array

Convenience method to return an array of calling public_send(method_name) on it's children

Returns:

  • (Array)

    results of public_send(method_name) in a flattened array



31
32
33
34
35
# File 'lib/csv_row_model/model/children.rb', line 31

def children_public_send(method_name)
  self.class.has_many_relationships.keys.map do |relation_name|
    public_send(relation_name).map(&method_name)
  end.flatten(1)
end

#deep_public_send(method_name) ⇒ Array

Convenience method to return an array of calling public_send(method_name) on itself and it's children

Returns:

  • (Array)

    results of public_send(method_name) in a flattened array



40
41
42
43
# File 'lib/csv_row_model/model/children.rb', line 40

def deep_public_send(method_name)
  result = [public_send(method_name)]
  result + children_public_send(method_name)
end