Class: CBOR::Transform_jr

Inherits:
Transform show all
Defined in:
lib/cbor-transform-j.rb

Instance Method Summary collapse

Methods inherited from Transform

#transform, #transform_array, #transform_bool, #transform_bytes, #transform_float, #transform_integer, #transform_nil, #transform_simple, #transform_tag, #transform_text

Instance Method Details

#transform_hash(obj) ⇒ Object

>> CBOR::Transform_jr.new(1).transform(JSON.parse(JSON.generate(a = CBOR::Transform_j.new(1).transform([1, “a”, “b”.b, CBOR::Simple.new(2), CBOR::Tagged.new(1, 2), 1, 2=> 3, {3=>4=>5}]))))

> [1, “a”, “b”, #<struct CBOR::Simple value=2>, #<struct CBOR::Tagged tag=1, value=2>, 2=>3, {3=>4=>5}]

>> a

> [1, “a”, :“@@!b”=>“Yg”, :“@@!s”=>2, :“@@!t1”=>2, “@@!:2”=>3, “@@!:{"@@!:3":4”=>5}]



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/cbor-transform-j.rb', line 44

def transform_hash(obj)
  if obj.size == 1 && obj.keys.first =~ /\A@@!([a-z].*)/
    cookie = $1
    value = obj.values.first
    case cookie
    when "s"
      CBOR::Simple.new(value)
    when "b"
      ::Base64.urlsafe_decode64(value)
    when /\At(\d+)\z/
      CBOR::Tagged.new($1.to_i, transform(value))
    else
      fail ArgumentError.new("Unknown CBOR-JSON encoding @@!#{cookie}")
    end
  else
    Hash[obj.map {|k, v| [ transform(
                             if k =~ /\A@@!:(.*)\z/
                               JSON.parse($1)
                             else
                               k
                             end), transform(v)]}]
  end
end