LoginSignup
2
5

More than 5 years have passed since last update.

Ruby on RailsでProtocol Buffersを使う

Last updated at Posted at 2017-05-28

RailsでProtocol Buffersを使用する

RailsでProtocol Buffersを使用するのに結構ハマったのでメモ

準備

rprotocコマンドのため、インストール
gem install ruby_protobuf

railsにインストールするため、Gemfileに以下を記述する
gem 'ruby_protobuf'

Gemfileの中身をインストール
bundle install

ProtocolBuffersをRubyに変換する

key_value.proto
message KeyValue {
    required string key = 1;
    optional string value = 2;
}

以下を実行してprotoファイルをRubyのコードに変換する
rprotoc key_value.proto

すると以下のようなファイルが作られるのでapp/modelsの中に配置する

key_value.pb.rb
### Generated by rprotoc. DO NOT EDIT!
### <proto file: key_value.proto>
# message KeyValue {
#       required string key = 1;
#       optional string value = 2;
# }
require 'protobuf/message/message'
require 'protobuf/message/enum'
require 'protobuf/message/service'
require 'protobuf/message/extend'

class KeyValue < ::Protobuf::Message
  defined_in __FILE__
  required :string, :key, 1
  optional :string, :value, 2

実際に使ってみる

sample.rb
require "key_value.pb"

# Railsならこのようにクラスの初期値が可
kv1 = KeyValue.new(key: "key1", value: "val1")

# serialize
kvstr = kv1.serialize_to_string

# deserialize
kv2 = KeyValue.new.parse_from_string(kvstr)

puts kv2[:key]
# => key1

# Protocol Buffersで使えるメソッド
puts KeyValue.new.methods
# => [:value, :key, :value=, :key=, :==, :[], :[]=, :inspect, :to_hash, :to_s, :clone, :dup, :initialized?, :fields, :clear!, :has_field?, :serialize_to_string, :parse_from_string, :get_field, :get_field_by_tag, :get_field_by_name, :each_field, :parse_from, :parse_from_file, :serialize_to, :serialize_to_file, :merge_from, :to_json, :`, :to_yaml, :to_yaml_properties, :blank?, :present?, :presence, :psych_to_yaml, :as_json, :acts_like?, :to_param, :to_query, :deep_dup, :duplicable?, :in?, :presence_in, :instance_values, :instance_variable_names, :with_options, :html_safe?, :pretty_print, :pretty_print_cycle, :pretty_print_instance_variables, :pretty_print_inspect, :require_dependency, :unloadable, :require_or_load, :load_dependency, :try, :try!, :instance_of?, :kind_of?, :is_a?, :tap, :public_send, :singleton_method, :class_eval, :remove_instance_variable, :define_singleton_method, :method, :public_method, :instance_variable_set, :extend, :to_enum, :enum_for, :gem, :<=>, :===, :=~, :!~, :pretty_inspect, :eql?, :respond_to?, :freeze, :object_id, :send, :display, :byebug, :debugger, :suppress_warnings, :nil?, :hash, :class, :singleton_class, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variable_get, :instance_variables, :instance_variable_defined?, :!, :!=, :__send__, :equal?, :instance_eval, :instance_exec, :__id__]
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5