Class: HashWithIndifferentAccess

Inherits:
Hash
  • Object
show all
Defined in:
lib/stella/core_ext.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

Methods inherited from Hash

#dump, #flatten, from_array, #to_http_params, #to_json

Constructor Details

#initialize(hash = {}) ⇒ HashWithIndifferentAccess

:nodoc:



30
31
32
33
34
35
# File 'lib/stella/core_ext.rb', line 30

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


76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/stella/core_ext.rb', line 76

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



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

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

#[]=(key, value) ⇒ Object



41
42
43
# File 'lib/stella/core_ext.rb', line 41

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

#delete(key) ⇒ Object



45
46
47
# File 'lib/stella/core_ext.rb', line 45

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

#merge(other) ⇒ Object



53
54
55
# File 'lib/stella/core_ext.rb', line 53

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

#merge!(other) ⇒ Object



57
58
59
60
61
62
# File 'lib/stella/core_ext.rb', line 57

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

#values_at(*indices) ⇒ Object



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

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