./lib/clean-hash/base.rb in clean-hash-0.3.1 vs ./lib/clean-hash/base.rb in clean-hash-0.4.0
- old
+ new
@@ -20,20 +20,46 @@
def to_ary
[@data]
end
def [] key
- __value_for key.to_s
+ 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' % key
+ 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)
- @data[key.to_sym] = value
+
+ 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
- __value_for name
+ self[name]
true
rescue NoMethodError
false
end
@@ -47,59 +73,31 @@
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('=', '')
-
- __error_set if @is_strict && !key?(m)
-
- value = args.first
-
- 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
-
- m = m.to_sym if @data[m].nil?
-
- @data[m] = value
+ self[m] = args.first
elsif m.end_with?('?')
begin
- !__value_for(m.sub('?', '')).nil?
+ !self[m.sub('?', '')].nil?
rescue NoMethodError
false
end
else
- __value_for m
+ self[m]
end
end
private
-
- def __value_for name
- data = @data[name.to_s]
- data = @data[name.to_sym] if data.nil?
-
- if data.nil?
- if @is_strict && !keys.include?(name.to_sym)
- raise NoMethodError, 'Clean hash: key "%s" not found' % name
- else
- nil
- end
- elsif data.is_a?(Hash)
- CleanHash.new data, @mode
- else
- data
- end
- end
def __error_set
raise NoMethodError, 'Clean hash: setting a key value is not allowedß'
end
end