Module: Protoable::Persistence::ClassMethods

Defined in:
lib/protoable/persistence.rb

Instance Method Summary collapse

Instance Method Details

#_filter_attribute_fields(proto) ⇒ Object

Filters accessible attributes that exist in the given protobuf message’s fields or have column transformers defined for them.

Returns a hash of attribute fields with their respective values.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/protoable/persistence.rb', line 13

def _filter_attribute_fields(proto)
  fields = proto.to_hash
  fields.select! { |key, value| proto.has_field?(key) && !proto.get_field_by_name(key).repeated? }

  attributes = self.new.attributes.keys - protected_attributes.to_a

  attribute_fields = attributes.inject({}) do |hash, column_name|
    symbolized_column = column_name.to_sym

    if fields.has_key?(symbolized_column) ||
      _protobuf_column_transformers.has_key?(symbolized_column)
      hash[symbolized_column] = fields[symbolized_column]
    end

    hash
  end

  attribute_fields
end

#attributes_from_proto(proto) ⇒ Object

Creates a hash of attributes from a given protobuf message.

It converts and transforms field values using the field converters and column transformers, ignoring repeated and nil fields.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/protoable/persistence.rb', line 38

def attributes_from_proto(proto)
  attribute_fields = _filter_attribute_fields(proto)

  attributes = attribute_fields.inject({}) do |hash, (key, value)|
    if _protobuf_column_transformers.has_key?(key)
      hash[key] = _protobuf_column_transformers[key].call(proto)
    else
      hash[key] = _protobuf_convert_fields_to_columns(key, value)
    end

    hash
  end

  attributes
end

#create_from_proto(proto) {|attributes| ... } ⇒ Object

Creates an object from the given protobuf message, if it’s valid. The newly created object is returned if it was successfully saved or not.

Yields:

  • (attributes)


57
58
59
60
61
62
63
64
65
66
# File 'lib/protoable/persistence.rb', line 57

def create_from_proto(proto)
  attributes = attributes_from_proto(proto)

  yield(attributes) if block_given?

  record = self.new(attributes)

  record.save! if record.valid?
  return record
end