Class: Code::Object::Json
Constant Summary collapse
- CLASS_DOCUMENTATION =
{ name: "Json", description: "parses json text and serializes values as json text.", examples: [ "Json.parse(\"{}\")", "Json.generate({ a: 1 })", "Json.generate([1, 2], { pretty: true })" ] }.freeze
- CLASS_FUNCTIONS =
{ "parse" => { name: "parse", description: "returns a value parsed from json text, or nothing when parsing fails.", examples: [ "Json.parse(\"{}\")", "Json.parse(\"[1,2]\")", "Json.parse(\"bad json\")" ] }, "generate" => { name: "generate", description: "returns json text for a value, optionally formatted for readability.", examples: [ "Json.generate({ a: 1 })", "Json.generate([1, 2])", "Json.generate({ a: 1 }, { pretty: true })" ] } }.freeze
Class Method Summary collapse
- .call(**args) ⇒ Object
- .code_generate(value, pretty: nil) ⇒ Object
- .code_parse(value) ⇒ Object
- .function_documentation(scope) ⇒ Object
Class Method Details
.call(**args) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/code/object/json.rb', line 44 def self.call(**args) code_operator = args.fetch(:operator, nil).to_code code_arguments = args.fetch(:arguments, []).to_code code_value = code_arguments.code_first case code_operator.to_s when "parse" sig(args) { String } code_parse(code_value) when "generate" sig(args) { [Object, { pretty: Object::Boolean.maybe }] } if code_arguments.code_second.something? code_generate( code_value, pretty: code_arguments.code_second.code_get(:pretty) ) else code_generate(code_value) end else super end end |
.code_generate(value, pretty: nil) ⇒ Object
78 79 80 |
# File 'lib/code/object/json.rb', line 78 def self.code_generate(value, pretty: nil) value.to_code.code_to_json(pretty: pretty) end |
.code_parse(value) ⇒ Object
69 70 71 72 73 74 75 76 |
# File 'lib/code/object/json.rb', line 69 def self.code_parse(value) code_value = value.to_code parsed = ::JSON.parse(code_value.raw) parsed.to_code rescue JSON::ParserError Nothing.new end |
.function_documentation(scope) ⇒ Object
38 39 40 41 42 |
# File 'lib/code/object/json.rb', line 38 def self.function_documentation(scope) return CLASS_FUNCTIONS if scope == :class {} end |