Sha256: 0507838251374e34385800d5d8634819d0a96c8f5dcef2033cd313b0e72a9c84

Contents?: true

Size: 1.72 KB

Versions: 2

Compression:

Stored size: 1.72 KB

Contents

require 'ar_protobuf_store/version'

require 'ar_protobuf_store/railtie.rb' if defined?(Rails)

module ArProtobufStore
  autoload(:CodekitchenProtobufParser,
           "ar_protobuf_store/codekitchen_protobuf_parser")
  autoload(:ProtobufParser,
           "ar_protobuf_store/protobuf_parser")

  def self.included(base)
    base.extend(ClassMethods)
  end

  def self.find_parser!(pb_class)
    if defined?(ProtocolBuffers) && ::ProtocolBuffers::Message > pb_class
      return ArProtobufStore::CodekitchenProtobufParser.new(pb_class)
    elsif defined?(Protobuf) && ::Protobuf::Message > pb_class
      return ArProtobufStore::ProtobufParser.new(pb_class)
    else
      raise "Could not identify protocol buffer library for #{pb_class}"
    end
  end

  module ClassMethods
    def protobuf_store(store_attribute, pb_class, options={})
      parser = ArProtobufStore.find_parser!(pb_class)
      serialize(store_attribute, parser)
      protobuf_store_accessor(store_attribute, parser.extract_fields(options[:accessors]))
    end

    def protobuf_store_accessor(store_attribute, *keys)
      Array(keys).flatten.each do |key|
        name = key[:name]
        coercer = case key[:type]
                  when :int
                    ".to_i"
                  when :float
                    ".to_f"
                  when :string
                    ".to_s"
                  else
                    ""
                  end
        class_eval <<-"END_EVAL", __FILE__, __LINE__
          def #{name}=(value)
            self.#{store_attribute}_will_change!
            self.#{store_attribute}.#{name} = value#{coercer}
          end
          def #{name}
            self.#{store_attribute}.#{name}
          end
        END_EVAL
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ar_protobuf_store-0.2.0 lib/ar_protobuf_store.rb
ar_protobuf_store-0.1.0 lib/ar_protobuf_store.rb