Sha256: f6bce2d976daaa656b4ee5ebb9d010ba16b4ff8e0e24733d40b0f5a4cb2fed65

Contents?: true

Size: 1.51 KB

Versions: 5

Compression:

Stored size: 1.51 KB

Contents

# frozen_string_literal: true

require 'active_support/core_ext/hash/indifferent_access'
require 'ostruct'

module EacRubyUtils
  class OptionsConsumer
    DEFAULT_OPTIONS = { validate: true, ostruct: false }.with_indifferent_access.freeze

    def initialize(data)
      @data = data.with_indifferent_access
    end

    def consume(key, default_value = nil, &block)
      return default_value unless data.key?(key)

      value = data.delete(key)
      value = yield(value) if block
      value
    end

    # If last argument is a Hash it is used a options.
    # Options:
    # * +validate+: validate after consume.
    # * +ostruct+: return a [OpenStruct] instead a [Hash].
    # @return [Hash] (Default) or [OpenStruct].
    def consume_all(*keys)
      options = consume_all_extract_options(keys)
      result = consume_all_build_result(keys, options.fetch(:ostruct))
      validate if options.fetch(:validate)
      result
    end

    def validate
      return if data.empty?

      raise "Invalid keys: #{data.keys}"
    end

    def left_data
      data.dup
    end

    private

    attr_reader :data

    def consume_all_extract_options(keys)
      options = DEFAULT_OPTIONS
      options = options.merge(keys.pop.with_indifferent_access) if keys.last.is_a?(Hash)
      options
    end

    def consume_all_build_result(keys, ostruct)
      if ostruct
        ::OpenStruct.new(keys.index_with { |key| consume(key) }) # rubocop:disable Style/OpenStructUse
      else
        keys.map { |key| consume(key) }
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
eac_ruby_utils-0.124.0 lib/eac_ruby_utils/options_consumer.rb
eac_tools-0.97.2 sub/eac_ruby_utils/lib/eac_ruby_utils/options_consumer.rb
eac_ruby_utils-0.123.0 lib/eac_ruby_utils/options_consumer.rb
eac_ruby_utils-0.121.0 lib/eac_ruby_utils/options_consumer.rb
eac_ruby_utils-0.120.0 lib/eac_ruby_utils/options_consumer.rb