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) ⇒ Hash|Enumerator
Yield to block for each method on the object, passing method name and value as parameters to the block.
-
#empty? ⇒ true|false
Return false if no methods exist on the object.
-
#initialize(state = nil) ⇒ JSOS
constructor
A new instance of JSOS.
-
#keys ⇒ Array<Symbol>
Return all method names on the object.
-
#to_a ⇒ Array
(also: #to_ary)
Convert the object to an Array.
-
#to_h ⇒ Hash
Convert the object to a Hash.
-
#to_json ⇒ String
Convert the object to a JSON string.
-
#values ⇒ Array
Return all method values on the object.
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.
100 101 102 |
# File 'lib/jsos.rb', line 100 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) ⇒ Hash|Enumerator
Yield to block for each method on the object, passing method name and value as parameters to the block.
80 81 82 |
# File 'lib/jsos.rb', line 80 def each &block self.to_h.each{ |k, v| yield k, v } end |
#empty? ⇒ true|false
Return false if no methods exist on the object. Otherwise, true.
93 94 95 |
# File 'lib/jsos.rb', line 93 def empty? @table.empty? end |
#keys ⇒ Array<Symbol>
Return all method names on the object.
66 67 68 |
# File 'lib/jsos.rb', line 66 def keys self.to_h.keys end |
#to_a ⇒ Array Also known as: to_ary
Convert the object to an Array.
86 87 88 |
# File 'lib/jsos.rb', line 86 def to_a self.to_h.to_a end |
#to_h ⇒ Hash
Convert the object to a Hash.
52 53 54 55 56 |
# File 'lib/jsos.rb', line 52 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
Convert the object to a JSON string.
60 61 62 |
# File 'lib/jsos.rb', line 60 def to_json self.to_h.to_json end |
#values ⇒ Array
Return all method values on the object.
72 73 74 |
# File 'lib/jsos.rb', line 72 def values self.to_h.values end |