make nested properties work better

This commit is contained in:
wvengen 2014-09-02 14:43:45 +02:00
parent 1a3b690757
commit 10a193add3
2 changed files with 17 additions and 9 deletions

View file

@ -109,15 +109,7 @@ class FoodsoftConfig
# @return [Boolean] Whether storing succeeded (fails when key is not allowed to be set in database). # @return [Boolean] Whether storing succeeded (fails when key is not allowed to be set in database).
def []=(key, value) def []=(key, value)
return false unless allowed_key?(key) return false unless allowed_key?(key)
# try to figure out type ... value = normalize_value value
value = case value
when 'true' then true
when 'false' then false
when /^[-+0-9]+$/ then value.to_i
when /^[-+0-9.]+([eE][-+0-9]+)?$/ then value.to_f
when '' then nil
else value
end
# then update database # then update database
if config[key] == value or (config[key].nil? and value == false) if config[key] == value or (config[key].nil? and value == false)
# delete (ok if it was already deleted) # delete (ok if it was already deleted)
@ -254,5 +246,20 @@ class FoodsoftConfig
cfg cfg
end end
# Normalize value recursively (which can be entered as strings, but we want to store it properly)
def normalize_value(value)
value = value.map(&:normalize_value) if value.is_a? Array
value = Hash[ value.to_a.map{|a| [a[0], normalize_value(a[1])]} ] if value.is_a? Hash
case value
when 'true' then true
when 'false' then false
when /^[-+0-9]+$/ then value.to_i
when /^[-+0-9.]+([eE][-+0-9]+)?$/ then value.to_f
when '' then nil
else value
end
end
end end
end end

View file

@ -38,6 +38,7 @@ describe 'admin/configs', type: :feature do
def get_full_config def get_full_config
cfg = FoodsoftConfig.to_hash.deep_dup cfg = FoodsoftConfig.to_hash.deep_dup
cfg.each {|k,v| v.reject! {|k,v| v.blank?} if v.is_a? Hash} cfg.each {|k,v| v.reject! {|k,v| v.blank?} if v.is_a? Hash}
cfg.reject! {|k,v| v.blank?}
cfg cfg
end end