Sha256: beb65e83ce4c0a0c4063087219625d4e0dd5bbb545c699d43ba379ea6980e046

Contents?: true

Size: 1.91 KB

Versions: 6

Compression:

Stored size: 1.91 KB

Contents

require "pathname"
require "yaml"

module Rmpd

  class Config

    DEFAULT_HOSTNAME = "localhost"
    DEFAULT_PORT = 6600
    DEFAULT_PASSWORD = nil

    attr_accessor :hostname, :password, :port
    alias_method :host, :hostname

    def initialize(config_file=nil)
      case config_file
      when String, Pathname
        config = YAML::load_file(config_file)
      when File, StringIO
        config = YAML::load(config_file)
      else
        config = {}
      end
      puts "env: #{detected_env}" if env_detected? && $DEBUG
      config = config[detected_env] if env_detected?
      puts "config: #{config.inspect}" if $DEBUG
      init_host_and_password(config)
      init_port(config)
    end


    private

    HOSTNAME_RE = /(.*)@(.*)/


    def detected_env
      if defined?(Rails)
        Rails.env
      elsif ENV.include?("APP_ENV")
        ENV["APP_ENV"]
      elsif ENV.include?("RACK_ENV")
        ENV["RACK_ENV"]
      elsif ENV.include?("RAILS_ENV")
        ENV["RAILS_ENV"]
      end
    end

    def env_detected?
      !!detected_env
    end

    def init_host_and_password(config)
      if config["hostname"]
        @hostname = parse_hostname(config["hostname"])
        @password = parse_password(config["hostname"])
      elsif ENV["MPD_HOST"]
        @hostname = parse_hostname(ENV["MPD_HOST"])
        @password = parse_password(ENV["MPD_HOST"])
      else
        @hostname = DEFAULT_HOSTNAME
        @password = DEFAULT_PASSWORD
      end
    end

    def init_port(config)
      if config["port"]
        @port = config["port"].to_i
      elsif ENV["MPD_PORT"]
        @port = ENV["MPD_PORT"].to_i
      else
        @port = DEFAULT_PORT
      end
    end

    def parse_hostname(hostname)
      if HOSTNAME_RE === hostname
        $~[2]
      else
        hostname
      end
    end

    def parse_password(hostname)
      if HOSTNAME_RE === hostname
        $~[1]
      else
        nil
      end
    end

  end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rmpd-1.1.5 lib/rmpd/config.rb
rmpd-1.1.4 lib/rmpd/config.rb
rmpd-1.1.3 lib/rmpd/config.rb
rmpd-1.1.2 lib/rmpd/config.rb
rmpd-1.1.1 lib/rmpd/config.rb
rmpd-1.1.0 lib/rmpd/config.rb