Class: OptParseBuilder::ArgumentValues

Inherits:
Object
  • Object
show all
Defined in:
lib/opt_parse_builder/argument_values.rb

Overview

Like OpenStruct, in that it allows access as through either a Hash or a Struct, but raises an error if you try to read a value that has not been set.

Strings and symbols may be interchanged freely for hash access.

A value may only by set using hash syntax:

arg_values = ArgumentValues.new
arg_values[:one] = 1
arg_values["two"] = 2

But may be retrieved using hash syntax:

arg_values["one"]    # => 1
arg_values[:two]     # => 2

or struct syntax:

arg_values.one    # => 1
arg_values.two    # => 2

Instance Method Summary collapse

Constructor Details

#initializeArgumentValues

Create an empty instance.


27
28
29
# File 'lib/opt_parse_builder/argument_values.rb', line 27

def initialize
  @h = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

:nodoc:


54
55
56
57
# File 'lib/opt_parse_builder/argument_values.rb', line 54

def method_missing(method, *args) # :nodoc:
  return super unless has_key?(method)
  self[method]
end

Instance Method Details

#[](key) ⇒ Object

Get a value. The key may be either a string or a symbol. Raises KeyError if the collection does not have that key.


50
51
52
# File 'lib/opt_parse_builder/argument_values.rb', line 50

def [](key)
  @h.fetch(key.to_sym)
end

#[]=(key, value) ⇒ Object

Set a key to a value. The key may be either a string or a symbol.


44
45
46
# File 'lib/opt_parse_builder/argument_values.rb', line 44

def []=(key, value)
  @h[key.to_sym] = value
end

#empty?Boolean

Return true if the collection is empty.

Returns:

  • (Boolean)

32
33
34
# File 'lib/opt_parse_builder/argument_values.rb', line 32

def empty?
  @h.empty?
end

#has_key?(key) ⇒ Boolean

Return true if the collection contains the key, which may be either a symbol or a string.

Returns:

  • (Boolean)

38
39
40
# File 'lib/opt_parse_builder/argument_values.rb', line 38

def has_key?(key)
  @h.has_key?(key.to_sym)
end