Class: JsonStruct
- Inherits:
-
OpenStruct
- Object
- OpenStruct
- JsonStruct
- Defined in:
- lib/json_struct.rb
Instance Method Summary collapse
- #as_json(*args) ⇒ Object
-
#initialize(hash = nil) ⇒ JsonStruct
constructor
A new instance of JsonStruct.
- #to_h ⇒ Object
- #to_json ⇒ Object
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 |
# File 'lib/json_struct.rb', line 5 def initialize(hash = nil) @table = {} @hash_table = {} if hash recurse = proc { |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 } 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
62 63 64 |
# File 'lib/json_struct.rb', line 62 def as_json(*args) to_h end |
#to_h ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/json_struct.rb', line 41 def to_h op = {} @table.each_pair do |key, value| op[key] = if value.is_a?(Array) value.map do |item| if item.is_a?(self.class) item.to_h else item end end elsif value.is_a?(self.class) value.to_h else value end end op end |
#to_json ⇒ Object
66 67 68 |
# File 'lib/json_struct.rb', line 66 def to_json JSON.dump(to_h) end |