Class: Plines::DynamicStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/plines/dynamic_struct.rb

Overview

Transforms an arbitrarily deeply nested hash into a dot-syntax object. Useful as an alternative to a hash since it is “strongly typed” in the sense that fat-fingered property names result in a NoMethodError, rather than getting a nil as you would with a hash.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ DynamicStruct

Returns a new instance of DynamicStruct.



9
10
11
12
13
14
15
16
17
18
# File 'lib/plines/dynamic_struct.rb', line 9

def initialize(hash)
  @to_hash = hash
  @attribute_names = hash.keys.map(&:to_sym)

  hash.each do |key, value|
    value = method_value_for(value)
    define_singleton_method(key) { value }
    define_singleton_method("#{key}?") { !!value }
  end
end

Instance Attribute Details

#attribute_namesObject (readonly)

Returns the value of attribute attribute_names.



7
8
9
# File 'lib/plines/dynamic_struct.rb', line 7

def attribute_names
  @attribute_names
end

#to_hashObject (readonly)

Returns the value of attribute to_hash.



7
8
9
# File 'lib/plines/dynamic_struct.rb', line 7

def to_hash
  @to_hash
end