Class: RecursiveStruct

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/recursive-struct.rb

Instance Method Summary collapse

Constructor Details

#initialize(input = nil) ⇒ RecursiveStruct

Returns a new instance of RecursiveStruct.



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/recursive-struct.rb', line 5

def initialize(input = nil)
  @recursive_table = {}
  hash = input
  if hash
    hash.each do |key, value|
      if value.class == Hash
        @recursive_table[key] = RecursiveStruct.new(value)
        hash.delete(key)
      end
    end
  end
  super(hash) 
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(mid, *args) ⇒ Object

def new_ostruct_member(name)

name = name.to_sym
unless respond_to?(name)

if name.nil? define_singleton_method(name) { @recursive_table } else yield(name) if block_given? end

end
name

end



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/recursive-struct.rb', line 36

def method_missing(mid, *args)
  mname = mid.id2name
  len = args.length
  if mname.chomp!('=')
    super(mid, *args)
  elsif len == 0
    return @recursive_table[mid] if @recursive_table[mid]
    return @table[mid] if @table[mid]
    @recursive_table[mid] = RecursiveStruct.new
  else
    raise NoMethodError, "undefined method `#{mid}' for #{self}", caller(1)
  end
end

Instance Method Details

#to_aryObject



19
20
21
# File 'lib/recursive-struct.rb', line 19

def to_ary
  self.to_h.to_a
end