Methods

AppConfig::Storage::Postgres

Constants

DEFAULTS

Public Class Methods

new(options) click to toggle source
# 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

Public Instance Methods

save!() click to toggle source

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

# File lib/app_config/storage/postgres.rb, line 36
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.
    columns = data_hash.keys.join(', ')
    values = data_hash.map { |_, v| "'#{v}'" }.join(', ')
    save_query = "INSERT INTO #{@table} (#{columns}) VALUES (#{values})"
  end

  result = @connection.exec(save_query)
  result.result_status == PG::Constants::PGRES_COMMAND_OK
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.