Class: SafeHash
- Inherits:
-
BlankSlate
- Object
- BlankSlate
- SafeHash
show all
- Defined in:
- lib/rails_ext/micelaneous/safe_hash.rb
Defined Under Namespace
Classes: SafeNil
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(hash = {}) ⇒ SafeHash
Returns a new instance of SafeHash.
6
7
8
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 6
def initialize hash = {}
reinitialize hash
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m, *args) ⇒ Object
51
52
53
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 51
def method_missing m, *args
self[m, *args]
end
|
Instance Attribute Details
#hash ⇒ Object
Returns the value of attribute hash.
4
5
6
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 4
def hash
@hash
end
|
Instance Method Details
#[](key, *args) ⇒ Object
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 19
def [] key, *args
key = key.to_s
if key.last == '!'
key = key[0..key.size-2]
if (result = @hash[key]).eql? nil
raise "No key #{key}"
else
result
end
elsif key.last == '?'
key = key[0..key.size-2]
@hash.include? key
elsif (result = @hash[key]).eql? nil
if args.empty?
SafeNil.instance
else
return *args
end
else
result
end
end
|
#[]=(key, value) ⇒ Object
10
11
12
13
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 10
def []= key, value
value = SafeHash.new value if value.is_a? Hash
@hash[key.to_s] = value
end
|
#include?(key) ⇒ Boolean
15
16
17
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 15
def include? key
@hash.include? key.to_s
end
|
#inspect ⇒ Object
59
60
61
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 59
def inspect
@hash.inspect
end
|
#reinitialize(hash) ⇒ Object
42
43
44
45
46
47
48
49
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 42
def reinitialize hash
@hash = {}
hash.each do |k, v|
v = SafeHash.new v if v.is_a? Hash
@hash[k.to_s] = v
end
end
|
#to_h ⇒ Object
63
64
65
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 63
def to_h
@hash
end
|
#to_yaml(*args) ⇒ Object
55
56
57
|
# File 'lib/rails_ext/micelaneous/safe_hash.rb', line 55
def to_yaml *args
@hash.to_yaml *args
end
|