Class: PollEverywhere::CoreExt::HashWithIndifferentAccess

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

Constructor Details

#initialize(hash = {}) ⇒ HashWithIndifferentAccess

:nodoc:



13
14
15
16
17
18
# File 'lib/polleverywhere/core_ext.rb', line 13

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


59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/polleverywhere/core_ext.rb', line 59

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



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

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

#[]=(key, value) ⇒ Object



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

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

#delete(key) ⇒ Object



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

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

#merge(other) ⇒ Object



36
37
38
# File 'lib/polleverywhere/core_ext.rb', line 36

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

#merge!(other) ⇒ Object



40
41
42
43
44
45
# File 'lib/polleverywhere/core_ext.rb', line 40

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

#values_at(*indices) ⇒ Object



32
33
34
# File 'lib/polleverywhere/core_ext.rb', line 32

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