Class: EacRubyUtils::OptionsConsumer

Inherits:
Object
  • Object
show all
Defined in:
lib/eac_ruby_utils/options_consumer.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{ validate: true, ostruct: false }.with_indifferent_access.freeze

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ OptionsConsumer

Returns a new instance of OptionsConsumer.



10
11
12
# File 'lib/eac_ruby_utils/options_consumer.rb', line 10

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

Instance Method Details

#consume(key, default_value = nil, &block) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/eac_ruby_utils/options_consumer.rb', line 14

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

#consume_all(*keys) ⇒ Hash

If last argument is a Hash it is used a options. Options:

  • validate: validate after consume.

  • ostruct: return a [OpenStruct] instead a [Hash].

Returns:

  • (Hash)

    (Default) or [OpenStruct].



27
28
29
30
31
32
# File 'lib/eac_ruby_utils/options_consumer.rb', line 27

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

#left_dataObject



40
41
42
# File 'lib/eac_ruby_utils/options_consumer.rb', line 40

def left_data
  data.dup
end

#validateObject



34
35
36
37
38
# File 'lib/eac_ruby_utils/options_consumer.rb', line 34

def validate
  return if data.empty?

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