Class: CSVStepImporter::Node

Inherits:
Base
  • Object
show all
Defined in:
lib/csv_step_importer/node.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#ancestors, #assign_attributes, #inspect, #persisted?, #save, #save!, set, #to_s, #update

Constructor Details

#initialize(parent: nil, children: [], env: nil) ⇒ Node

Returns a new instance of Node.



15
16
17
18
19
20
21
# File 'lib/csv_step_importer/node.rb', line 15

def initialize(parent: nil, children: [], env: nil)
  super()

  self.env = build_env(env) if env
  self.parent = parent
  self.children = children
end

Instance Attribute Details

#childrenObject

Returns the value of attribute children.



5
6
7
# File 'lib/csv_step_importer/node.rb', line 5

def children
  @children
end

#envObject

Returns the value of attribute env.



8
9
10
# File 'lib/csv_step_importer/node.rb', line 8

def env
  @env
end

#parentObject

Returns the value of attribute parent.



6
7
8
# File 'lib/csv_step_importer/node.rb', line 6

def parent
  @parent
end

Instance Method Details

#add_children(children, prepend: false) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/csv_step_importer/node.rb', line 37

def add_children(children, prepend: false)
  children = Array(children) unless children.is_a?(Enumerable)

  children = children.collect do |child, sub_children|
    next child unless child.is_a?(Class)
    child.new parent: self, children: sub_children
  end.compact

  @children = prepend ? children + @children : @children + children
end

#build_env(env) ⇒ Object



23
24
25
# File 'lib/csv_step_importer/node.rb', line 23

def build_env(env)
  Struct.new(*env.keys).new(*env.values).freeze
end

#create_or_updateObject



48
49
50
# File 'lib/csv_step_importer/node.rb', line 48

def create_or_update
  children.empty? || children.all?(&:save)
end

#run_validations!Object

NOTE: the native after_validation seems not be able to influence the return value of run_validations! However, children should only be validated if the parent is valid



54
55
56
57
# File 'lib/csv_step_importer/node.rb', line 54

def run_validations!
  super
  errors.empty?
end

#validate_childrenObject



59
60
61
62
63
64
65
66
67
68
# File 'lib/csv_step_importer/node.rb', line 59

def validate_children
  return unless errors.empty?

  children.each do |child|
    next if child.valid?
    child.errors.each do |key, message|
      errors[key] << message
    end
  end
end