Class: JsonStruct

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/json_struct.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ JsonStruct

Returns a new instance of JsonStruct.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/json_struct.rb', line 5

def initialize(hash=nil)

  @table = {}
  @hash_table = {}

  if hash
    recurse = Proc.new do |item|
      values = []

      item.each do |val|
        if val.is_a?(Hash)
          values.push(self.class.new(val))
        elsif val.is_a?(Array)
          values.push(recurse.call(val))
        else
          values.push(val)
        end
      end

      item.clear
      item.push(*values)

      item
    end

    hash.each do |k,v|

      if v.is_a?(Array)
        recurse.call(v)
      end

      @table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
      @hash_table[k.to_sym] = v
      new_ostruct_member(k)

    end
  end
end

Instance Method Details

#as_json(*args) ⇒ Object



65
66
67
# File 'lib/json_struct.rb', line 65

def as_json(*args)
 to_h
end

#to_hObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/json_struct.rb', line 44

def to_h
  op = {}

  @table.each_pair do |key, value|
    if value.is_a?(Array)
      op[key] = value.map do |item|
        if item.is_a?(self.class)
          item.to_h
        else
          item
        end
      end
    elsif value.is_a?(self.class)
      op[key] = value.to_h
    else
      op[key] = value
    end
  end
  op
end

#to_jsonObject



69
70
71
# File 'lib/json_struct.rb', line 69

def to_json
  JSON.dump(to_h)
end