Class: AppConfig::Storage::Postgres

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

Constant Summary collapse

DEFAULTS =
{
  host:     'localhost',
  port:     5432,
  dbname:   'app_config',
  table:    'app_config',
  user:     nil,
  password: nil,
}

Instance Method Summary collapse

Methods inherited from Base

#method_missing, #to_hash

Constructor Details

#initialize(options) ⇒ Postgres

Returns a new instance of Postgres


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

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

  # HACK: Remove the `user` and `password` keys if they're nil, since `@options` is passed directly to `PG.connect`.
  @options.delete(:user) if @options[:user].nil?
  @options.delete(:password) if @options[:password].nil?

  @table = @options.delete(:table)

  setup_connection!
  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

Reload the data from storage. Returns `true`/`false`.


36
37
38
# File 'lib/app_config/storage/postgres.rb', line 36

def reload!
  fetch_data!
end

#save!Object

Saves the data to Postgres. Returns `true`/`false`.


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
71
72
73
74
75
76
# File 'lib/app_config/storage/postgres.rb', line 41

def save!
  # Build the `SET foo = 'bar', ...` string for the UPDATE query.
  data_hash = @data.to_h
  # Remove the primary key (id) from the SET attributes.
  data_hash.delete(:id)

  if @id  # Updating existing values.
    set_attrs = data_hash.map { |k, v| "#{k} = '#{v}'" }.join(', ')
    save_query = "UPDATE #{@table} SET #{set_attrs} WHERE id = #{@id}"
  else  # Creating a new row.
    if data_hash.empty?
      save_query = "INSERT INTO #{@table} DEFAULT VALUES"
    else
      columns = data_hash.keys.join(', ')
      values = data_hash.map { |_, v| "'#{v}'" }.join(', ')
      save_query = "INSERT INTO #{@table} (#{columns}) VALUES (#{values})"
    end
  end

  result = @connection.exec(save_query)

  if result.result_status == PG::Constants::PGRES_COMMAND_OK
    # Initial write (no rows exist), so we have to set @id.
    if result.cmd_status.split[0] == 'INSERT'
      @connection.exec("SELECT id FROM #{@table}") do |result|
        result.each { |row| @id = row['id'] }
      end

      fetch_data!
    end

    true
  else
    false
  end
end