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
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

Returns:

  • (true|false)


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

def empty?
  @table.empty?
end

#keysArray<Symbol>

Returns:

  • (Array<Symbol>)


63
64
65
# File 'lib/jsos.rb', line 63

def keys
  self.to_h.keys
end

#to_hHash

Returns:

  • (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_jsonString

Returns:

  • (String)


58
59
60
# File 'lib/jsos.rb', line 58

def to_json
  self.to_h.to_json
end

#valuesArray

Returns:

  • (Array)


68
69
70
# File 'lib/jsos.rb', line 68

def values
  self.to_h.values
end