Sha256: 6d25e01e74190369c22ebf21dd19b3d238dbf207b5d1c34297430426f5afbf1c

Contents?: true

Size: 1.8 KB

Versions: 3

Compression:

Stored size: 1.8 KB

Contents

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

    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

    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

    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

    private
    def default_value
      if @opts[:default].respond_to? :call
        @opts[:default].call
      elsif @opts[:default].duplicable?
        @opts[:default].dup
      else
        @opts[:default]
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ar_protobuf_store-1.0.2 lib/ar_protobuf_store/codekitchen_protobuf_parser.rb
ar_protobuf_store-1.0.1 lib/ar_protobuf_store/codekitchen_protobuf_parser.rb
ar_protobuf_store-1.0.0 lib/ar_protobuf_store/codekitchen_protobuf_parser.rb