Sha256: e5b6efef99d0eae2edd960b16ec15f3da76721cb633cd2faf808c86b2ee68581

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

module ParamStore
  class Wrapper
    def initialize(adapter_class)
      @adapter_class = adapter_class
    end

    def fetch(key, *args, &block)
      key = key.to_s
      unless cache.key?(key)
        # cache params to minimize number of requests
        cache[key] = adapter_instance.fetch(key, *args, &block)
      end
      cache[key]
    end

    def copy_to_env(*keys, require_keys: false)
      cache_all(*keys)

      require_keys!(*keys) if require_keys

      keys.each { |key| ENV[key] = cache[key] }
    end

    def require_keys!(*keys)
      cache_all(*keys)

      missing = keys.flatten.map!(&:to_s) - cache.keys

      return if missing.none?

      raise "Missing keys: #{missing.join(', ')}"
    end

    private

    attr_accessor :adapter, :cache

    def cache_all(*keys)
      keys.flatten.map!(&:to_s)
      adapter_instance.fetch_all(*keys).each do |key, value|
        cache[key] = value
      end
    end

    def cache
      @_cache ||= {}
    end

    def adapter_instance
      @_adapter_instance ||= @adapter_class.new
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
param_store-0.0.1 lib/param_store/wrapper.rb