Module: ActiveRemote::Serializers::Protobuf::ClassMethods

Defined in:
lib/active_remote/serializers/protobuf.rb

Instance Method Summary collapse

Instance Method Details

#build_message(message_class, attributes) ⇒ Object

Recursively build messages from a hash of attributes. TODO: Pull this functionality into the protobuf gem.



36
37
38
39
40
41
42
43
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/active_remote/serializers/protobuf.rb', line 36

def build_message(message_class, attributes)
  attributes.inject(message_class.new) do |message, (key, value)|
    if field = message.get_field_by_name(key) || message.get_ext_field_by_name(key)

      # Override the value based on the field type where issues
      # exist in the protobuf gem.
      #
      if field.repeated?
        collection = [ value ]
        collection.flatten!
        collection.compact!
        collection.map! { |value| coerce(value, field) }
        value = collection
      else
        value = coerce(value, field)
      end

      if field.message? && field.repeated?
        value = value.map do |attributes|
          attributes.is_a?(Hash) ? build_message(field.type, attributes) : attributes
        end
      elsif field.message?
        value = value.is_a?(Hash) ? build_message(field.type, value) : value
      end

      message.method("#{key}=").call(value)
    end

    message
  end
end

#coerce(value, field) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/active_remote/serializers/protobuf.rb', line 68

def coerce(value, field)
  return value if value.nil?
  return value.to_i if field.enum?

  protobuf_field_type = ::ActiveRemote::Serializers::Protobuf::ATTRIBUTE_TYPES[field.type]

  case 
  when protobuf_field_type == ::ActiveAttr::Typecasting::Boolean then
    if value == 1
      return true
    elsif value == 0
      return false
    end
  when protobuf_field_type == Integer then
    return value.to_i
  when protobuf_field_type == Float then
    return value.to_f
  when protobuf_field_type == String then
    return value.to_s
  end

  return value
end