Sha256: 11a7e765194a3a52570ec17ccce4eacc9e0a49dfdde5a844a883c286b610ad30

Contents?: true

Size: 1.18 KB

Versions: 2

Compression:

Stored size: 1.18 KB

Contents

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

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

    def copy_to_env(*keys, **opts)
      require_keys = opts.delete(:require_keys)

      cache_all(*keys, **opts)

      require_keys!(*keys, **opts) if require_keys

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

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

      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, **opts)
      keys.flatten.map!(&:to_s)
      adapter_instance.fetch_all(*keys, **opts).each do |key, value|
        cache[key] = value
      end
    end

    def cache
      @_cache ||= {}
    end

    def adapter_instance
      @_adapter_instance ||= @adapter_class.new(**@opts)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
param_store-1.0.1 lib/param_store/wrapper.rb
param_store-1.0.0 lib/param_store/wrapper.rb