Class: AppConfig::Storage::MySQL

Inherits:
Base
  • Object
show all
Defined in:
lib/app_config/storage/mysql.rb

Constant Summary collapse

DEFAULTS =
{
  host: 'localhost',
  port: 3306,
  database: 'app_config',
  table: 'app_config',
  username: nil,
  password: nil,
}

Instance Method Summary collapse

Methods inherited from Base

#method_missing, #to_hash

Constructor Details

#initialize(options) ⇒ MySQL

Returns a new instance of MySQL


17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/app_config/storage/mysql.rb', line 17

def initialize(options)
  # Allows passing `true` as an option, which uses the defaults.
  if options.is_a?(Hash)
    @options = DEFAULTS.merge(options)
  else
    @options = DEFAULTS
  end

  @table = @options.delete(:table)

  setup_client!
  fetch_data!
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class AppConfig::Storage::Base

Instance Method Details

#reload!Object


31
32
33
# File 'lib/app_config/storage/mysql.rb', line 31

def reload!
  fetch_data!
end

#save!Object


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
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/app_config/storage/mysql.rb', line 35

def save!
  data_hash = @data.to_h
  data_hash.delete(:id)

  if @id
    # Update existing row.
    set_attrs = data_hash.map do |k, v|
      if v.is_a?(TrueClass) || v.is_a?(FalseClass)
        "#{k} = #{v}"  # Don't quote booleans.
      else
        "#{k} = '#{v}'"
      end
    end.join(', ')
    save_query = "UPDATE #{@table} SET #{set_attrs} WHERE id = #{@id};"
  else
    # Create a new row.
    if data_hash.empty?
      # Use defaults.
      save_query = "INSERT INTO #{@table}(id) VALUES(NULL);"
    else
      columns = data_hash.keys.join(', ')
      values = data_hash.map do |_, v|
        if v.is_a?(TrueClass) || v.is_a?(FalseClass)
          "#{v}"  # Don't quote booleans.
        else
          "'#{v}'"
        end
      end.join(', ')

      save_query = "INSERT INTO #{@table} (#{columns}) VALUES (#{values});"
    end
  end

  @client.query(save_query)
  @client.affected_rows == 1
end