Class: Thor::CoreExt::HashWithIndifferentAccess

Inherits:
Hash
  • Object
show all
Defined in:
lib/thor/core_ext/hash_with_indifferent_access.rb

Overview

A hash with indifferent access and magic predicates.

hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true

hash[:foo]  #=> 'bar'
hash['foo'] #=> 'bar'
hash.foo?   #=> true

Instance Method Summary (collapse)

Constructor Details

- (HashWithIndifferentAccess) initialize(hash = {})

:nodoc:



14
15
16
17
18
19
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 14

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

- (Object) method_missing(method, *args, &block) (protected)

Magic predicates. For instance:

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


65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 65

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

- (Object) [](key)



21
22
23
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 21

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

- (Object) []=(key, value)



25
26
27
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 25

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

- (Object) delete(key)



29
30
31
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 29

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

- (Object) merge(other)



37
38
39
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 37

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

- (Object) merge!(other)



41
42
43
44
45
46
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 41

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

- (Object) to_hash

Convert to a Hash with String keys.



49
50
51
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 49

def to_hash
  Hash.new(default).merge!(self)
end

- (Object) values_at(*indices)



33
34
35
# File 'lib/thor/core_ext/hash_with_indifferent_access.rb', line 33

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