Class: JSOS
- Inherits:
-
OpenStruct
- Object
- OpenStruct
- JSOS
- Defined in:
- lib/jsos.rb
Overview
Parse or construct JSON strings with OpenStruct objects.
Setter methods add a key and a value to the object and are converted to JSON.
Getter methods represent the object keys and return their values.
Undefined getter methods act like setter methods. Their values become empty JSOS objects.
Undefined getters can be chained with setters to create nested JSON objects.
Instance Method Summary collapse
- #each(&block) ⇒ Object
- #empty? ⇒ true|false
-
#initialize(state = nil) ⇒ JSOS
constructor
A new instance of JSOS.
- #keys ⇒ Array<Symbol>
- #to_h ⇒ Hash
- #to_json ⇒ String
- #values ⇒ Array
Constructor Details
#initialize(state = nil) ⇒ JSOS
Returns a new instance of JSOS.
44 45 46 47 48 |
# File 'lib/jsos.rb', line 44 def initialize(state = nil) return super if state.nil? state_hash = state.is_a?(String) ? JSON.parse(state) : state super parse_state_hash(state_hash) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(methd, *args) ⇒ Object (private)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
84 85 86 |
# File 'lib/jsos.rb', line 84 def method_missing methd, *args methd.to_s.end_with?('=') ? super(methd, *args) : super(make_setter(methd), JSOS.new) end |
Instance Method Details
#each(&block) ⇒ Object
72 73 74 |
# File 'lib/jsos.rb', line 72 def each &block self.to_h.each{ |k, v| yield k, v } end |
#empty? ⇒ true|false
77 78 79 |
# File 'lib/jsos.rb', line 77 def empty? @table.empty? end |
#keys ⇒ Array<Symbol>
63 64 65 |
# File 'lib/jsos.rb', line 63 def keys self.to_h.keys end |
#to_h ⇒ Hash
51 52 53 54 55 |
# File 'lib/jsos.rb', line 51 def to_h @table.each_with_object({}) do |(key, value), new_hash| new_hash[key] = value.is_a?(JSOS) ? value.to_h : value end end |
#to_json ⇒ String
58 59 60 |
# File 'lib/jsos.rb', line 58 def to_json self.to_h.to_json end |
#values ⇒ Array
68 69 70 |
# File 'lib/jsos.rb', line 68 def values self.to_h.values end |