Sha256: c3aed40b60e5d12210ea32358a6958401a4c6ca84a9216823e90dddd88762875

Contents?: true

Size: 1.14 KB

Versions: 6

Compression:

Stored size: 1.14 KB

Contents

require "delivery_boy/config_error"

module DeliveryBoy
  class EnvConfigLoader
    KEY_PREFIX = "DELIVERY_BOY"

    def initialize(env, config)
      @env = env
      @config = config
      @loaded_keys = []
    end

    def string(name)
      set(name) {|value| value }
    end

    def symbol(name)
      set(name) {|value| value.to_sym }
    end

    def integer(name)
      set(name) do |value|
        begin
          Integer(value)
        rescue ArgumentError
          raise ConfigError, "#{value.inspect} is not an integer"
        end
      end
    end

    def string_list(name)
      set(name) {|value| value.split(",") }
    end

    def validate!
      # Make sure the user hasn't made a typo and added a key we don't know
      # about.
      @env.keys.grep(/^#{KEY_PREFIX}_/).each do |key|
        unless @loaded_keys.include?(key)
          raise ConfigError, "unknown config variable #{key}"
        end
      end
    end

    private

    def set(name)
      key = "#{KEY_PREFIX}_#{name.upcase}"

      if @env.key?(key)
        value = yield @env.fetch(key)
        @config.set(name, value)
        @loaded_keys << key
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
delivery_boy-0.1.5 lib/delivery_boy/env_config_loader.rb
delivery_boy-0.1.4 lib/delivery_boy/env_config_loader.rb
delivery_boy-0.1.3 lib/delivery_boy/env_config_loader.rb
delivery_boy-0.1.2 lib/delivery_boy/env_config_loader.rb
delivery_boy-0.1.1 lib/delivery_boy/env_config_loader.rb
delivery_boy-0.1.0 lib/delivery_boy/env_config_loader.rb