Module: Interpol::DynamicStruct

Defined in:
lib/interpol/dynamic_struct.rb,
lib/interpol/hash_set_default_proc_18.rb

Overview

Hashie::Mash is awesome: it gives us dot/method-call syntax for a hash. This is perfect for dealing with structured JSON data. The downside is that Hashie::Mash responds to anything–it simply creates a new entry in the backing hash.

DynamicStruct freezes a Hashie::Mash so that it no longer responds to everything. This is handy so that consumers of this gem can distinguish between a fat-fingered field, and a field that is set to nil.

Constant Summary collapse

DEFAULT_PROC =
lambda do |hash, key|
  raise NoMethodError, "undefined method `#{key}' for #{hash.inspect}"
end
Mash =
Class.new(::Hashie::Mash) do
  undef sort
end

Class Method Summary collapse

Class Method Details

.new(source) ⇒ Object



21
22
23
24
25
# File 'lib/interpol/dynamic_struct.rb', line 21

def self.new(source)
  hash = Mash.new(source)
  recursively_freeze(hash)
  hash
end

.recursively_freeze(object) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/interpol/dynamic_struct.rb', line 27

def self.recursively_freeze(object)
  case object
    when Array
      object.each { |obj| recursively_freeze(obj) }
    when Hash
      set_default_proc_on(object)
      recursively_freeze(object.values)
  end
end

.set_default_proc_on(hash) ⇒ Object

Hash#default_proc= isn’t defined on 1.8; this is the best we can do.



4
5
6
# File 'lib/interpol/hash_set_default_proc_18.rb', line 4

def self.set_default_proc_on(hash)
  hash.default_proc = DEFAULT_PROC
end