Module: Interpol::DynamicStruct

Defined in:
lib/interpol/dynamic_struct.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

SAFE_METHOD_MISSING =
::Hashie::Mash.superclass.instance_method(:method_missing)
Mash =
Class.new(::Hashie::Mash) do
  undef sort
end

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &blk) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/interpol/dynamic_struct.rb', line 39

def method_missing(method_name, *args, &blk)
  if key = method_name.to_s[/\A([^?=]*)[?=]?\z/, 1]
    unless has_key?(key)
      return safe_method_missing(method_name, *args, &blk)
    end
  end

  super
end

Class Method Details

.extended(mash) ⇒ Object



25
26
27
# File 'lib/interpol/dynamic_struct.rb', line 25

def self.extended(mash)
  recursively_extend(mash)
end

.new(*args) ⇒ Object



19
20
21
22
23
# File 'lib/interpol/dynamic_struct.rb', line 19

def self.new(*args)
  Mash.new(*args).tap do |mash|
    mash.extend(self)
  end
end

.recursively_extend(object) ⇒ Object



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

def self.recursively_extend(object)
  case object
    when Array
      object.each { |v| recursively_extend(v) }
    when Mash
      object.extend(self) unless object.is_a?(self)
      object.each { |_, v| recursively_extend(v) }
  end
end