Sha256: 17d9affba43a60aa4414274bd0210acf04c8e1536c6c45babf7db297f9894e8d

Contents?: true

Size: 1.69 KB

Versions: 6

Compression:

Stored size: 1.69 KB

Contents

# private
module Simple::SQL::Config
  extend self

  # parse a DATABASE_URL, return PG::Connection settings.
  def parse_url(url)
    require "uri"

    raise ArgumentError, "Invalid URL #{url.inspect}" unless url.is_a?(String)
    raise ArgumentError, "Invalid URL #{url.inspect}" unless url =~ /^postgres(ql)?s?:\/\//

    uri = URI.parse(url)
    raise ArgumentError, "Invalid URL #{url}" unless uri.hostname && uri.path

    config = {
      dbname: uri.path.sub(%r{^/}, ""),
      host:   uri.hostname
    }
    config[:port] = uri.port if uri.port
    config[:user] = uri.user if uri.user
    config[:password] = uri.password if uri.password
    config[:sslmode] = uri.scheme == "postgress" || uri.scheme == "postgresqls" ? "require" : "prefer"
    config
  end

  # determines the database_url from either the DATABASE_URL environment setting
  # or a config/database.yml file.
  def determine_url
    ENV["DATABASE_URL"] || database_url_from_database_yml
  end

  private

  def database_url_from_database_yml
    abc = read_database_yml
    username, password, host, port, database, password = abc.values_at "username", "password", "host", "port", "database", "password"

    username_and_password = [ username, password ].compact.join(":")
    host_and_port = [ host, port ].compact.join(":")
    "postgres://#{username_and_password}@#{host_and_port}/#{database}"
  end

  def read_database_yml
    require "yaml"
    database_config = YAML.load_file "config/database.yml"
    env = ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"

    database_config[env] ||
    database_config["defaults"] ||
    raise("Invalid or missing database configuration in config/database.yml for #{env.inspect} environment")
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
simple-sql-0.2.6 lib/simple/sql/config.rb
simple-sql-0.2.5 lib/simple/sql/config.rb
simple-sql-0.2.4 lib/simple/sql/config.rb
simple-sql-0.2.3 lib/simple/sql/config.rb
simple-sql-0.2.2 lib/simple/sql/config.rb
simple-sql-0.2.1 lib/simple/sql/config.rb