Class: CSVStepImporter::Model::Model

Inherits:
Node
  • Object
show all
Defined in:
lib/csv_step_importer/model/model.rb

Direct Known Subclasses

ImportableModel

Instance Attribute Summary collapse

Attributes inherited from Node

#children, #env, #parent

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

#add_children, #build_env, #create_or_update, #run_validations!, #validate_children

Methods inherited from Base

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

Constructor Details

#initialize(**attributes) ⇒ Model

Logic



24
25
26
27
28
29
30
# File 'lib/csv_step_importer/model/model.rb', line 24

def initialize(**attributes)
  super **attributes

  add_daos
  filter_daos! if composite_key_columns
  add_model_children
end

Instance Attribute Details

#dao_valuesObject

Returns the value of attribute dao_values.



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

def dao_values
  @dao_values
end

Class Method Details

.cache_key(pluralize: false) ⇒ Object

Configuration



36
37
38
39
# File 'lib/csv_step_importer/model/model.rb', line 36

def self.cache_key(pluralize: false)
  key = name.underscore.gsub("/", "_")
  (pluralize ? key.pluralize : key.singularize).to_sym
end

Instance Method Details

#add_daosObject



61
62
63
64
65
66
67
68
69
# File 'lib/csv_step_importer/model/model.rb', line 61

def add_daos
  dao_node_children = rows.collect do |row|
    build_daos_for_row row
  end.flatten.compact

  link_rows_to_daos daos: dao_node_children

  dao_node.add_children dao_node_children
end

#add_model_childrenObject

Logic



45
46
47
# File 'lib/csv_step_importer/model/model.rb', line 45

def add_model_children
  add_children dao_node, prepend: true
end

#build_daos_for_row(row) ⇒ Object

can return nil, a single object or an array of objects



72
73
74
# File 'lib/csv_step_importer/model/model.rb', line 72

def build_daos_for_row(row)
  dao_class.new parent: dao_node, row: row
end

#dao_nodeObject



57
58
59
# File 'lib/csv_step_importer/model/model.rb', line 57

def dao_node
  @dao_node ||= CSVStepImporter::Node.new parent: self
end

#daosObject



49
50
51
# File 'lib/csv_step_importer/model/model.rb', line 49

def daos
  dao_node.children
end

#filter_daos!Object

TODO a possible feature would be to add validation errors if the duplicates do not match in all columns (columns other than the composite key)



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/csv_step_importer/model/model.rb', line 77

def filter_daos!
  unique_daos = {}

  daos.keep_if do |dao|
    hash = dao.values_for(composite_key_columns).hash
    keep = (unique_daos[hash] ||= dao) == dao

    # unlink to be deleted dao and add a link to
    dao.unlink! replace_with: unique_daos[hash] unless keep

    keep
  end
end


91
92
93
# File 'lib/csv_step_importer/model/model.rb', line 91

def link_rows_to_daos(daos:)
  daos.each(&:link!)
end