Class: ArProtobufStore::ProtobufParser

Inherits:
Object
  • Object
show all
Defined in:
lib/ar_protobuf_store/protobuf_parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(pb_class, opts = nil) ⇒ ProtobufParser

Returns a new instance of ProtobufParser.



3
4
5
6
7
8
9
# File 'lib/ar_protobuf_store/protobuf_parser.rb', line 3

def initialize(pb_class, opts = nil)
  @klass = pb_class
  @opts = opts || {}
  @opts = {
    :default => Proc.new { pb_class.new() }
  }.merge(opts || {})
end

Instance Method Details

#dump(str) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ar_protobuf_store/protobuf_parser.rb', line 27

def dump(str)
  str.serialize_to_string
rescue Exception
  if defined?(Rails)
    Rails.logger.error("Failed to serialize: #{$!}")
  else
    puts "Failed to serialize: #{$!}"
  end

  return nil
end

#extract_fields(accessors = nil) ⇒ Object



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
67
# File 'lib/ar_protobuf_store/protobuf_parser.rb', line 39

def extract_fields(accessors = nil)
  fields = @klass.fields
  fields = fields.values if fields.respond_to?(:values)

  if !accessors.nil?
    accessors = accessors.dup.map { |a| a.to_s }
    fields = fields.select { |field|
      accessors.include?(field.name.to_s)
    }
  end

  typed_fields = fields.map do |field|
    t = case field
        when Protobuf::Field::StringField
          :string
        when Protobuf::Field::BoolField
          :bool
        when Protobuf::Field::IntegerField, Protobuf::Field::Uint32Field, Protobuf::Field::Uint64Field
          :int
        when Protobuf::Field::FloatField
          :float
        else
          nil
        end
    { :name => field.name.to_s, :type => t }
  end

  return typed_fields
end

#load(str) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/ar_protobuf_store/protobuf_parser.rb', line 11

def load(str)
  if str.nil?
    return default_value
  else
    return @klass.new.tap { |o| o.parse_from_string(str) }
  end
rescue Exception
  if defined?(Rails)
    Rails.logger.error("Failed to deserialize: #{$!}")
  else
    puts "Failed to deserialize: #{$!}"
  end

  return default_value
end