Class: Ettin::Options

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/ettin/options.rb

Overview

An object that holds configuration settings / options

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Options

Returns a new instance of Options.



14
15
16
17
18
# File 'lib/ettin/options.rb', line 14

def initialize(hash)
  @hash = hash
  @hash.deep_transform_keys! {|key| key.to_s.to_sym }
  @hash.default = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/ettin/options.rb', line 20

def method_missing(method, *args, &block)
  super(method, *args, &block) unless respond_to?(method)
  if bang?(method) && !key?(debang(method))
    raise KeyError, "key #{debang(method)} not found"
  else
    self[debang(method)]
  end
end

Instance Method Details

#[](key) ⇒ Object



46
47
48
# File 'lib/ettin/options.rb', line 46

def [](key)
  convert(hash[Key.new(key)])
end

#[]=(key, value) ⇒ Object



50
51
52
# File 'lib/ettin/options.rb', line 50

def []=(key, value)
  hash[Key.new(key)] = value
end

#eachObject



64
65
66
# File 'lib/ettin/options.rb', line 64

def each
  hash.each {|k, v| yield k, convert(v) }
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


59
60
61
# File 'lib/ettin/options.rb', line 59

def eql?(other)
  to_h == other.to_h
end

#key?(key) ⇒ Boolean Also known as: has_key?

Returns:

  • (Boolean)


37
38
39
# File 'lib/ettin/options.rb', line 37

def key?(key)
  hash.key?(Key.new(key))
end

#merge!(other) ⇒ Object



42
43
44
# File 'lib/ettin/options.rb', line 42

def merge!(other)
  hash.deep_merge!(other.to_h, overwrite_arrays: true)
end

#respond_to_missing?(method, include_all = false) ⇒ Boolean

We respond to:

  • all methods our parents respond to

  • all methods that are mostly alpha-numeric: /^[a-zA-Z_0-9]*$/

  • all methods that are mostly alpha-numeric + !: /^[a-zA-Z_0-9]*!$/

Returns:

  • (Boolean)


33
34
35
# File 'lib/ettin/options.rb', line 33

def respond_to_missing?(method, include_all = false)
  super(method, include_all) || /^[a-zA-Z_0-9]*\!?$/.match(method.to_s)
end

#to_hObject Also known as: to_hash



54
55
56
# File 'lib/ettin/options.rb', line 54

def to_h
  hash
end