Class: JSOS

Inherits:
OpenStruct
  • Object
show all
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.

Examples:

JSOS.new("{\"foo\":\"bar\"}")
jsos = JSOS.new
jsos.foo = "bar"
jsos.to_json
#=> "{\"foo\":\"bar\"}"
jsos = JSOS.new("{\"foo\":\"bar\"}")
jsos.foo
#=> "bar"
jsos = JSOS.new
jsos.foo
jsos.to_json
#=> "{\"foo\":{}}"
jsos = JSOS.new
jsos.abc.foo = "bar"
jsos.to_json
#=> "{\"abc\":{\"foo\":\"bar\"}}"

Instance Method Summary collapse

Constructor Details

#initialize(state = nil) ⇒ JSOS

Returns a new instance of JSOS.

Parameters:

  • state (String|Hash) (defaults to: nil)

    defaults to nil



44
45
46
# File 'lib/jsos.rb', line 44

def initialize(state = nil)
  state.is_a?(String) ? super(JSON.parse state) : super(state)
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.



78
79
80
# File 'lib/jsos.rb', line 78

def method_missing methd, *args
  methd.to_s.end_with?('=') ? super(methd, *args) : super(make_setter(methd), JSOS.new)
end

Instance Method Details

#empty?true|false

Returns:

  • (true|false)


71
72
73
# File 'lib/jsos.rb', line 71

def empty?
  @table.empty?
end

#keysArray<Symbol>

Returns:

  • (Array<Symbol>)


61
62
63
# File 'lib/jsos.rb', line 61

def keys
  self.to_h.keys
end

#to_hHash

Returns:

  • (Hash)


49
50
51
52
53
# File 'lib/jsos.rb', line 49

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_jsonString

Returns:

  • (String)


56
57
58
# File 'lib/jsos.rb', line 56

def to_json
  self.to_h.to_json
end

#valuesArray

Returns:

  • (Array)


66
67
68
# File 'lib/jsos.rb', line 66

def values
  self.to_h.values
end