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
-
.has_many(relation_name, row_model_class) ⇒ Object
Defines a relationship between a row model (only one relation per model for now).
Instance Method Summary collapse
-
#append_child(source, options = {}) ⇒ Model
Appends child to the parent and returns it.
-
#child? ⇒ Boolean
Returns true, if the instance is a child.
-
#children_public_send(method_name) ⇒ Array
Convenience method to return an array of calling
public_send(method_name)on it's children. -
#deep_public_send(method_name) ⇒ Array
Convenience method to return an array of calling
public_send(method_name)on itself and it's children.
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).
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
17 18 19 20 21 22 23 24 25 26 |
# File 'lib/csv_row_model/model/children.rb', line 17 def append_child(source, ={}) self.class.has_many_relationships.each do |relation_name, child_class| child_row_model = child_class.new(source, .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
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
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
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 |