Deep freeze IndifferentAccess.

This commit is contained in:
Thomas Reynolds 2014-07-14 13:19:34 -07:00
parent 332ce2bebc
commit 1f3e2043cb
9 changed files with 74 additions and 49 deletions

View file

@ -1,3 +1,5 @@
require 'middleman-core/contracts'
module Middleman
module Util
# A hash with indifferent access and magic predicates.
@ -10,11 +12,17 @@ module Middleman
# hash.foo? #=> true
#
class HashWithIndifferentAccess < ::Hash #:nodoc:
include Contracts
Contract Hash => Any
def initialize(hash={})
super()
hash.each do |key, value|
self[convert_key(key)] = value
hash.each do |key, val|
self[key] = recursively_enhance(val)
end
freeze
end
def [](key)
@ -73,6 +81,23 @@ module Middleman
self[method]
end
end
private
Contract Any => Frozen[Any]
def recursively_enhance(data)
if data.is_a? HashWithIndifferentAccess
data
elsif data.is_a? Hash
self.class.new(data)
elsif data.is_a? Array
data.map(&method(:recursively_enhance)).freeze
elsif data.frozen?
data
else
data.dup.freeze
end
end
end
end
end