Class: HashWithIndifferentAccess

Inherits:
Hash
  • Object
show all
Defined in:
lib/hashwithindifferentaccess.rb

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ HashWithIndifferentAccess



5
6
7
8
9
10
# File 'lib/hashwithindifferentaccess.rb', line 5

def initialize(hash={})
  super()
  hash.each do |key, value|
    self[convert_key(key)] = value
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Magic predicates. For instance:

options.force?                  # => !!options['force']
options.shebang                 # => "/usr/lib/local/ruby"
options.test_framework?(:rspec) # => options[:test_framework] == :rspec


51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/hashwithindifferentaccess.rb', line 51

def method_missing(method, *args, &block)
  method = method.to_s
  if method =~ /^(\w+)\?$/
    if args.empty?
      !!self[$1]
    else
      self[$1] == args.first
    end
  else
    self[method]
  end
end

Instance Method Details

#[](key) ⇒ Object



12
13
14
# File 'lib/hashwithindifferentaccess.rb', line 12

def [](key)
  super(convert_key(key))
end

#[]=(key, value) ⇒ Object



16
17
18
# File 'lib/hashwithindifferentaccess.rb', line 16

def []=(key, value)
  super(convert_key(key), value)
end

#delete(key) ⇒ Object



20
21
22
# File 'lib/hashwithindifferentaccess.rb', line 20

def delete(key)
  super(convert_key(key))
end

#merge(other) ⇒ Object



28
29
30
# File 'lib/hashwithindifferentaccess.rb', line 28

def merge(other)
  dup.merge!(other)
end

#merge!(other) ⇒ Object



32
33
34
35
36
37
# File 'lib/hashwithindifferentaccess.rb', line 32

def merge!(other)
  other.each do |key, value|
    self[convert_key(key)] = value
  end
  self
end

#values_at(*indices) ⇒ Object



24
25
26
# File 'lib/hashwithindifferentaccess.rb', line 24

def values_at(*indices)
  indices.collect { |key| self[convert_key(key)] }
end