Module: Jsonify::Generate
- Defined in:
- lib/jsonify/generate.rb
Overview
Provides a set of functions for creating JsonValues from Ruby objects.
Class Method Summary collapse
- .array_value(vals) ⇒ Object
- .object_value(hash) ⇒ Object
- .pair_value(key, val = nil) ⇒ Object
-
.value(val) ⇒ Object
Coerces the given value into a JsonValue (or subclass), String, or Number.
Class Method Details
.array_value(vals) ⇒ Object
44 45 46 |
# File 'lib/jsonify/generate.rb', line 44 def array_value(vals) JsonArray.new(Array(vals).map{ |v| value v }) end |
.object_value(hash) ⇒ Object
38 39 40 41 42 |
# File 'lib/jsonify/generate.rb', line 38 def object_value(hash) json_object = JsonObject.new hash.each { |key,val| json_object.add( pair_value(key, val) ) } json_object end |
.pair_value(key, val = nil) ⇒ Object
34 35 36 |
# File 'lib/jsonify/generate.rb', line 34 def pair_value(key,val=nil) JsonPair.new(key,value(val)) end |
.value(val) ⇒ Object
Coerces the given value into a JsonValue (or subclass), String, or Number.
The coercion rules are based on the type (class) of the value as follows:
-
JsonValue
=> no coercion -
String
=> no coercion -
Numeric
=> no coercion -
TrueClass
=> JsonTrue ( true ) -
FalseClass
=> JsonFalse ( false ) -
NilClass
=> JsonNull ( null ) -
Array
=> JsonArray ( [1,2,3] ) -
Hash
=> JsonObject ({"\a":1,\"b\":2}
) -
else
=> #to_s
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/jsonify/generate.rb', line 22 def value(val) case val when JsonValue, String, Numeric; val when TrueClass; @json_true ||= JsonTrue.new when FalseClass; @json_false ||= JsonFalse.new when NilClass; @json_null ||= JsonNull.new when Array; array_value val when Hash; object_value val else val.to_s end end |