Class: ArProtobufStore::CodekitchenProtobufParser

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

Instance Method Summary collapse

Constructor Details

#initialize(pb_class, opts = nil) ⇒ CodekitchenProtobufParser

Returns a new instance of CodekitchenProtobufParser.



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

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

Instance Method Details

#dump(str) ⇒ Object



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

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



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
# File 'lib/ar_protobuf_store/codekitchen_protobuf_parser.rb', line 38

def extract_fields(accessors = nil)
  fields = @klass.fields.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 ProtocolBuffers::Field::StringField
          :string
        when ProtocolBuffers::Field::BoolField
          :bool
        when ProtocolBuffers::Field::VarintField
          :int
        when ProtocolBuffers::Field::FloatField, ProtocolBuffers::Field::DoubleField
          :float
        else
          nil
        end
    { :name => field.name.to_s, :type => t }
  end

  return typed_fields
end

#load(str) ⇒ Object



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

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

  return default_value
end