Class: Ambry::HashProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/ambry/hash_proxy.rb

Overview

Wrapper around hash instances that allows values to be accessed as symbols, strings or method invocations. It behaves similary to OpenStruct, with the fundamental difference being that you instantiate one HashProxy instance and reassign its Hash during a loop in order to avoid creating garbage.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol) ⇒ Object

Allows accessing a hash attribute as a method.


14
15
16
17
18
19
20
21
22
# File 'lib/ambry/hash_proxy.rb', line 14

def method_missing(symbol)
  if hash.key?(symbol)
    hash[symbol]
  elsif hash.key?(symbol.to_s)
    hash[symbol.to_s]
  else
    raise NoMethodError
  end
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash


7
8
9
# File 'lib/ambry/hash_proxy.rb', line 7

def hash
  @hash
end

Class Method Details

.with(hash, &block) ⇒ Object


9
10
11
# File 'lib/ambry/hash_proxy.rb', line 9

def self.with(hash, &block)
  new.with(hash, &block)
end

Instance Method Details

#[](key) ⇒ Object

Allows accessing a hash attribute as hash key, either a string or symbol.


25
26
27
28
29
30
# File 'lib/ambry/hash_proxy.rb', line 25

def [](key)
  if hash.key?(key)           then hash[key]
  elsif hash.key?(key.to_sym) then hash[key.to_sym]
  elsif hash.key?(key.to_s)   then hash[key.to_s]
  end
end

#clearObject

Remove the hash.


37
38
39
# File 'lib/ambry/hash_proxy.rb', line 37

def clear
  @hash = nil
end

#key?(key) ⇒ Boolean


32
33
34
# File 'lib/ambry/hash_proxy.rb', line 32

def key?(key)
  hash.key?(key) or hash.key?(key.to_sym) or hash.key?(key.to_s)
end

#using(hash) ⇒ Object

Assign the value to hash and return self.


42
43
44
# File 'lib/ambry/hash_proxy.rb', line 42

def using(hash)
  @hash = hash ; self
end

#with(hash, &block) ⇒ Object

Set the hash to use while calling the block. When the block ends, the hash is unset.


48
49
50
# File 'lib/ambry/hash_proxy.rb', line 48

def with(hash, &block)
  yield using hash ensure clear
end