Class: CleanHash
- Inherits:
-
Object
show all
- Defined in:
- lib/clean-hash/types/mutex_type.rb,
lib/clean-hash/base.rb,
lib/clean-hash/deep_merge.rb,
lib/clean-hash/hash_pollute.rb,
lib/clean-hash/types/safe_type.rb,
lib/clean-hash/types/strict_type.rb,
lib/clean-hash/types/struct_type.rb,
lib/clean-hash/types/indifferent_type.rb
Overview
Creates dynamic struct based on arguments
Defined Under Namespace
Classes: DeepMerge, Indifferent, MutexHash, Safe, Strict
Constant Summary
collapse
- STRUCTS =
{}
Class Method Summary
collapse
Class Method Details
.create(type, data = {}) ⇒ Object
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# File 'lib/clean-hash/base.rb', line 2
def self.create type, data={}
case type
when :indifferent
::CleanHash::Indifferent.new data
when :safe
::CleanHash::Safe.new data
when :strict
::CleanHash::Strict.new data
when :stuct
::CleanHash.create_strut data
when :mutex
::CleanHash::MutexHash.new data
else
raise ArgumentError, 'Unsupported type: %s' % type
end
end
|
.create_struct(hash) ⇒ Object
6
7
8
9
10
11
12
13
14
15
16
17
|
# File 'lib/clean-hash/types/struct_type.rb', line 6
def self.create_struct hash
raise ArgumentError.new('Not a hash') unless hash.is_a?(Hash)
name = 'DynStruct_' + hash.keys.join('_')
STRUCTS[name] ||= ::Struct.new(name, *hash.keys.sort)
STRUCTS[name].new.tap do |o|
hash.each do |k, v|
o.send('%s=' % k, v) unless v.nil?
end
end
end
|
.pollute! ⇒ Object
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
# File 'lib/clean-hash/hash_pollute.rb', line 2
def self.pollute!
::Hash.class_eval do
def deep_merge hash
klass = ::CleanHash::DeepMerge
klass[deep_clone].deep_merge klass[hash]
end
def deep_clone
Marshal.load(Marshal.dump(self))
end
def to_ch mode=nil
if mode.is_a?(Array)
mode.each { |el| self[el] = nil if self[el].nil? }
::CleanHash.create_struct self
else
mode ||= :indifferent
::CleanHash.create mode, self
end
end
end
end
|