Class: Impex::HistoryManager::ActiveRecord

Inherits:
Base
  • Object
show all
Defined in:
lib/impex/history_managers/active_record.rb

Instance Method Summary collapse

Methods inherited from Base

#initialize, #load

Constructor Details

This class inherits a constructor from Impex::HistoryManager::Base

Instance Method Details

#filter_data_with_history(row) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/impex/history_managers/active_record.rb', line 6

def filter_data_with_history(row)
  reference = row.columns[@options[:history_references][row.table.to_sym].to_s || "reference"]
  select_column = row.columns.keys.join(", ")
  whitelist = @whitelist[row.table]

  query = <<-SQL.gsub(/[\n\t\s]+/, ' ')
    SELECT *
    FROM #{history_table} AS cih
    WHERE
      cih.`reference`=#{quote(reference)}
      AND cih.`table`=#{quote(row.table)}
  SQL

  query << "AND cih.`key` IN (#{quote(whitelist).join(',')})" unless whitelist.nil? || whitelist.empty?

  records = connection.exec_query(query).to_hash
  return row if records.empty?

  history = Hash.new { |h, k| h[k] = [] }

  records.each { |record| history[record["key"]] << record["value"] }

  row.columns.each do |column_name, column_value|
    row.columns.delete(column_name) if history[column_name].include?(column_value)
  end
  row
end

#update_history(row) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/impex/history_managers/active_record.rb', line 34

def update_history(row)
  reference = row.columns.delete(@options[:history_references][row.table.to_sym].to_s || "reference")
  return if row.columns.empty?

  query = <<-SQL.gsub(/[\n\t\s]+/, ' ')
    INSERT INTO
    #{history_table}
    (`reference`, `table`, `key`, `value`)
    VALUES
  SQL

  records = []
  row.columns.each do |column_name, column_value|
    next unless whitelist_include?(row.table, column_name)
    values = [
      reference,
      row.table,
      column_name, column_value
    ].map { |value| quote(value) }.join(',')

    records << "(#{values})"
  end

  query << "#{records.join(',')};"
  connection.execute(query) unless records.empty?
end