Class: HashDial::HashDialler

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_dial/hash_dialler.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash, *lookup) ⇒ HashDialler

Returns a new instance of HashDialler.



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/hash_dial/hash_dialler.rb', line 9

def initialize(hash, *lookup)
	if hash.is_a?(Hash)
		@hash = hash
	else
		@hash = {}
	end
	@lookup = []
	if lookup.length > 0
		dial!(*lookup)
	end
end

Instance Method Details

#+(key) ⇒ Object



67
68
69
# File 'lib/hash_dial/hash_dialler.rb', line 67

def +(key)
	return dial!(key)
end

#-(key) ⇒ Object



70
71
72
# File 'lib/hash_dial/hash_dialler.rb', line 70

def -(key)
	return undial!(key)
end

#[](key) ⇒ Object

The preferred way to build up your dialling list. Access HashDialler as if it were a Hash, e.g. hash[b]. This does not actually return any value, rather it dials those keys (awaiting a call).



64
65
66
# File 'lib/hash_dial/hash_dialler.rb', line 64

def [](key)
	return dial!(key)
end

#call(default = nil) ⇒ Object

Digs into the hash to the list of keys specified by dialling. Returns nil or default if specified.

Parameters:

  • default (defaults to: nil)

    What to return if no key is found.



35
36
37
38
39
40
41
42
# File 'lib/hash_dial/hash_dialler.rb', line 35

def call(default = nil)
	begin
		value = @hash.dig(*@lookup)
	rescue
		value = default
	end
	return value
end

#dial!(*keys) ⇒ Object

Adds a hash key to the list of nested keys to try, one level deeper.

Parameters:

  • keys

    The key to add. Multiple arguments would add multiple keys.



25
26
27
28
29
# File 'lib/hash_dial/hash_dialler.rb', line 25

def dial!(*keys)
	#unless key.is_a(Symbol) || key.is_a(String)
	@lookup += keys
	return self
end

#hangupObject

Return the original hash object.



45
46
47
# File 'lib/hash_dial/hash_dialler.rb', line 45

def hangup
	return @hash
end

#undial!(*keys) ⇒ Object

Remove keys from the dialling list.

Parameters:

  • keys

    If specified, these keys would be removed from wherever they appear in the dialling list. Otherwise, the last added key is removed.



53
54
55
56
57
58
59
60
# File 'lib/hash_dial/hash_dialler.rb', line 53

def undial!(*keys)
	if keys.length > 0
		@lookup -= keys
	elsif @lookup.length > 0
		@lookup.pop
	end
	return self
end