Module: FlattenRecord::Flattener::ClassMethods

Defined in:
lib/flatten_record/flattener.rb

Instance Method Summary collapse

Instance Method Details

#create_with(normal) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/flatten_record/flattener.rb', line 30

def create_with(normal)
  if normal_model.eql?(normal.class)
    destroy_with(normal)
    records = flattener_meta.denormalize(normal.reload, self.new)
    records.each(&:save)
    records
  else
    destroy_with(normal)
    find_normals(normal).each do |n|
      create_with(n)
    end
  end
end

#denormalize(normal_model, definition_hash) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/flatten_record/flattener.rb', line 20

def denormalize(normal_model, definition_hash)
  definition = Definition.new(definition_hash)

  root_node = Meta::RootNode.new(normal_model, self)
  root_node.build(definition)

  self.flattener_meta = root_node
  self.normal_model = root_node.target_model
end

#destroy_with(normal) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/flatten_record/flattener.rb', line 49

def destroy_with(normal)
  if normal_model.eql?(normal.class)
    records = find_with(normal)
    records.each{|r| r.destroy }
  else
    # update associated model
    find_normals(normal).each do |n|
      update_with(n)
    end
  end
  records
end

#find_node(type, value) ⇒ Object



82
83
84
# File 'lib/flatten_record/flattener.rb', line 82

def find_node(type, value)
  flattener_meta.traverse_by(type, value)
end

#find_normals(normal) ⇒ Object



62
63
64
65
66
67
68
69
70
71
# File 'lib/flatten_record/flattener.rb', line 62

def find_normals(normal)
  return normal if normal_model.eql?(normal.class)
  
  records = find_with(normal)
  id_name = flattener_meta.id_column.name
  normal_id_name = flattener_meta.id_column.column.name
  
  ids = records.collect{|c| c.send(id_name.to_sym) }
  normal_model.where(normal_id_name => ids)
end

#find_with(normal) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/flatten_record/flattener.rb', line 73

def find_with(normal)
  node = find_node(:target_model, normal.class)

  id_name = node.id_column.name 
  normal_id_name = node.id_column.column.name

  self.where(id_name => normal.send(normal_id_name))
end

#update_with(normal) ⇒ Object



44
45
46
47
# File 'lib/flatten_record/flattener.rb', line 44

def update_with(normal)
  destroy_with(normal)
  create_with(normal)
end