./lib/clean-hash/base.rb in clean-hash-0.4.1 vs ./lib/clean-hash/base.rb in clean-hash-0.5.0
- old
+ new
@@ -1,104 +1,18 @@
class CleanHash
- def initialize data, mode=nil
- @data = data
- @mode = mode
-
- case mode
+ def self.create type, data={}
+ case type
+ when :indifferent
+ ::CleanHash::Indifferent.new data
when :safe
- @is_safe = true
+ ::CleanHash::Safe.new data
+ when :strict
+ ::CleanHash::Strict.new data
+ when :stuct
+ ::CleanHash.create_strut data
+ when :mutex
+ ::CleanHash::MutexHash.new data
else
- @is_strict = true if mode
+ raise ArgumentError, 'Unsupported type: %s' % type
end
end
-
- # for debug
- def to_json
- JSON.pretty_generate @data
- end
-
- # for puts
- def to_ary
- [@data]
- end
-
- def [] key
- data = @data[key.to_sym]
- data = @data[key.to_s] if data.nil?
-
- if data.nil?
- if @is_strict && !keys.include?(key.to_sym)
- raise NoMethodError, 'Clean hash: key "%s" not found (%s)' % [key, keys]
- else
- nil
- end
- elsif data.is_a?(Hash)
- CleanHash.new data, @mode
- else
- data
- end
- end
-
- def []= key, value
- key = key.to_sym unless key.class == Symbol
-
- __error_set if @is_strict && !key?(key)
-
- if @is_safe
- value = value.to_s if value.is_a?(Symbol)
-
- unless value.nil? || value.is_a?(Hash) || value.is_a?(Numeric) || value.is_a?(String)
- raise ArgumentError.new('Unsupported safe type: %s' % value.class)
- end
- end
-
- @data.delete(key.to_s)
-
- @data[key] = value
- end
-
- def key? name
- self[name]
- true
- rescue NoMethodError
- false
- end
-
- def keys
- @data.keys
- end
-
- def values
- @data.values
- end
-
- def to_h
- @data
- end
-
- def to_json *args
- @data.to_json *args
- end
-
- def method_missing name, *args
- m = name.to_s
-
- if m.end_with?('=')
- m = m.sub('=', '')
- self[m] = args.first
- elsif m.end_with?('?')
- begin
- !self[m.sub('?', '')].nil?
- rescue NoMethodError
- false
- end
- else
- self[m]
- end
- end
-
- private
-
- def __error_set
- raise NoMethodError, 'Clean hash: setting a key value is not allowedß'
- end
-end
+end
\ No newline at end of file