Class: SafeHash
- Inherits:
-
BasicObject
- Defined in:
- lib/ruby_ext/more/safe_hash.rb
Overview
Defined Under Namespace
Classes: SafeNil
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(hash = {}) ⇒ SafeHash
Returns a new instance of SafeHash.
8
9
10
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 8
def initialize hash = {}
reinitialize hash
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m, obj = ::NotDefined, &b) ⇒ Object
66
67
68
69
70
71
72
73
74
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 66
def method_missing m, obj = ::NotDefined, &b
raise "invalid usage, can't pass block to (:#{m})!" if b
last = m[-1]
if last == '='
self[m[0..-2]] = obj
else
self[m, obj]
end
end
|
Instance Attribute Details
Returns the value of attribute hash.
4
5
6
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 4
def hash
@hash
end
|
Instance Method Details
#[](key, if_not_exist = ::NotDefined) ⇒ Object
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 32
def [] key, if_not_exist = ::NotDefined
last = key[-1]
if last == '!'
key = key[0..-2].to_sym
if @hash.include? key
@hash[key]
else
raise "no key :#{key}"
end
elsif last == '?'
key = key[0..-2].to_sym
@hash.include? key
else
key = key.to_sym
if @hash.include? key
@hash[key]
elsif if_not_exist == ::NotDefined
SafeNil.new key
else
return if_not_exist
end
end
end
|
#[]=(key, value) ⇒ Object
12
13
14
15
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 12
def []= key, value
value = ::SafeHash.new value if value.is_a? ::Hash
@hash[key.to_sym] = value
end
|
#delete(key) ⇒ Object
84
85
86
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 84
def delete key
@hash.delete key.to_sym
end
|
#include?(key) ⇒ Boolean
def set! key, value
value = ::SafeHash.new value if value.is_a? ::Hash
@hash[key.to_sym] = value
end def set *args; raise “you probably mistyped :set! method!” end
23
24
25
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 23
def include? key
@hash.include? key.to_sym
end
|
80
81
82
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 80
def inspect
@hash.inspect
end
|
#is_a_safe_hash? ⇒ Boolean
103
104
105
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 103
def is_a_safe_hash?
true
end
|
27
28
29
30
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 27
def tap &b
b.call self
self
end
|
#to_hash(options = {}) ⇒ Object
Also known as:
to_h
deep conversion, check and converts nested SafeHashes to Hashes
89
90
91
92
93
94
95
96
97
98
99
100
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 89
def to_hash options = {}
r = {}
@hash.each do |k, v|
k = k.to_s if options[:to_s]
r[k] = if v.respond_to :is_a_safe_hash?
v.to_hash options
else
v
end
end
r
end
|
#to_yaml(*args) ⇒ Object
76
77
78
|
# File 'lib/ruby_ext/more/safe_hash.rb', line 76
def to_yaml *args
@hash.to_yaml *args
end
|