Class: Snapshots::TableLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/snapshots/database_loader.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection, table) ⇒ TableLoader

Returns a new instance of TableLoader.



29
30
31
32
33
# File 'lib/snapshots/database_loader.rb', line 29

def initialize(connection, table)
  @table  = table
  @connection = connection
  @columns = @connection.columns(table)
end

Class Method Details

.load(connection, table, &proc) ⇒ Object



25
26
27
# File 'lib/snapshots/database_loader.rb', line 25

def self.load(connection, table, &proc)
  new(connection, table).load(&proc)
end

Instance Method Details

#attributes_with_quotes(attributes = {}) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/snapshots/database_loader.rb', line 51

def attributes_with_quotes(attributes={})
  quoted = []
  @columns.each do |column|
    value = attributes[column.name.to_sym]
    quoted.push @connection.quote(value, column)
  end
  quoted
end

#insert(attributes = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/snapshots/database_loader.rb', line 40

def insert(attributes={})
  quoted_attributes = attributes_with_quotes(attributes)
  
  return if quoted_attributes.empty?
  
  column_names = @columns.collect { |column| "#{@table}.#{column.name}" }
  statement = "INSERT INTO #{@table} (#{column_names.join(', ')}) VALUES(#{quoted_attributes.join(', ')})"
  
  @connection.insert(statement, "#{@table} Create")
end

#load {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



35
36
37
38
# File 'lib/snapshots/database_loader.rb', line 35

def load
  @connection.execute("DELETE FROM #{@table}")
  yield(self)
end