Class: SearchLogger::Persistence

Inherits:
Object
  • Object
show all
Defined in:
lib/search_logger/persistence.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection_config = { host: "localhost", username: "root", database: "search_logger" }) ⇒ Persistence

Returns a new instance of Persistence.



8
9
10
11
12
# File 'lib/search_logger/persistence.rb', line 8

def initialize(connection_config = { host: "localhost", username: "root", database: "search_logger" })
  @data = []
  @connection_config = connection_config
  establish_connection
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



5
6
7
# File 'lib/search_logger/persistence.rb', line 5

def client
  @client
end

#connection_configObject

Returns the value of attribute connection_config.



5
6
7
# File 'lib/search_logger/persistence.rb', line 5

def connection_config
  @connection_config
end

#data(data = []) ⇒ Object (readonly)

sets up the operation properties



20
21
22
# File 'lib/search_logger/persistence.rb', line 20

def data
  @data
end

#table(table = nil) ⇒ Object

Returns the value of attribute table.



5
6
7
# File 'lib/search_logger/persistence.rb', line 5

def table
  @table
end

Instance Method Details

#establish_connectionObject



14
15
16
# File 'lib/search_logger/persistence.rb', line 14

def establish_connection
  @client = ::Mysql2::Client.new(@connection_config)
end

#load_data(client = @client) ⇒ Object



62
63
64
65
66
# File 'lib/search_logger/persistence.rb', line 62

def load_data(client = @client)
  [].tap do |e|
    client.query(load_to_sql).each(symbolize_keys: true) { |row| e << row }
  end
end

#load_to_sqlObject



58
59
60
# File 'lib/search_logger/persistence.rb', line 58

def load_to_sql
  "SELECT * FROM #{table}"
end

#save(client = @client) ⇒ Object



54
55
56
# File 'lib/search_logger/persistence.rb', line 54

def save(client = @client)
  client.query(save_to_sql)
end

#save_to_sqlObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/search_logger/persistence.rb', line 33

def save_to_sql
  fields, values = [], []
  fields_complete = false
  # gathers fields and values
  data.each_with_index do |e, index|
    values[index] = []
    e.each do |key, value|
      fields << key.to_s unless fields_complete
      values[index] << client.escape(value.to_s)
    end
    fields_complete = true
  end

  # creates values string
  each_record_values = []
  values.each do |e|
    each_record_values << "('#{e.join("', '")}')"
  end
  sql = "INSERT INTO #{table} (#{fields.join(', ')}) VALUES #{each_record_values.join(', ')}"
end