class Thrift::Types::Known::Any::MetaCodec

Public Class Methods

new(klass) click to toggle source
   # File lib/thrift/types/known/any.rb
22 def initialize(klass)
23   @klass = klass
24 end

Public Instance Methods

decode(buf, obj) click to toggle source
   # File lib/thrift/types/known/any.rb
30 def decode(buf, obj)
31   from_hash(obj, @klass.load(buf))
32 end
encode(obj) click to toggle source
   # File lib/thrift/types/known/any.rb
26 def encode(obj)
27   @klass.dump(to_hash(obj))
28 end

Private Instance Methods

from_hash(obj, hash) click to toggle source
   # File lib/thrift/types/known/any.rb
62 def from_hash(obj, hash)
63   return nil if hash.nil?
64 
65   obj.struct_fields.values.each do |field|
66     name = field[:name]
67     value = hash[name]
68 
69     obj.send("#{name}=", from_value_field(value, field)) if value
70   end
71 
72   obj
73 end
from_value_field(value, field) click to toggle source
   # File lib/thrift/types/known/any.rb
75 def from_value_field(value, field)
76   case field[:type]
77   when Thrift::Types::STRUCT
78     from_hash(field[:class].new, value)
79   when Thrift::Types::LIST
80     value.map { |vv| from_value_field(vv, field[:element]) }
81   when Thrift::Types::MAP
82     value.reduce({}) do |acc, (k, v)|
83       kv = from_value_field(k, field[:key])
84       vv = from_value_field(v, field[:value])
85       acc.merge(kv => vv)
86     end
87   else
88     value
89   end
90 end
to_hash(obj) click to toggle source
   # File lib/thrift/types/known/any.rb
36 def to_hash(obj)
37   to_hash_field(obj, type: Thrift::Types::STRUCT)
38 end
to_hash_field(value, field) click to toggle source
   # File lib/thrift/types/known/any.rb
40 def to_hash_field(value, field)
41   case field[:type]
42   when Thrift::Types::STRUCT
43     value.struct_fields.values.reduce({}) do |acc, sfield|
44       name = sfield[:name]
45       vv = value.send("#{name}?") ? to_hash_field(value.send(name), sfield) : nil
46       vv.nil? ? acc : acc.merge(name => vv)
47     end
48   when Thrift::Types::LIST
49     value.map { |vv| to_hash_field(vv, field[:element]) }
50   when Thrift::Types::MAP
51     value.reduce({}) do |acc, (k, v)|
52       kv = to_hash_field(k, field[:key])
53       vv = to_hash_field(v, field[:value])
54 
55       acc.merge(kv => vv)
56     end
57   else
58     value
59   end
60 end