1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rubyのclassでメンバ変数を一括でjson出力してRedisに登録する

Last updated at Posted at 2016-06-05

はじめに

Redisでrubyのクラス情報を一気に登録したい場合について調査した。
jsonにして登録するのが良さそうとのことなので、classのメンバ変数をまとめて、json化したい

rubyのメンバ変数の一括取得

rubyのメンバ変数を一括で取得するのに、便利なメソッドがある。
http://ref.xaio.jp/ruby/classes/object/instance_variables

リファレンスの内容を以下に抜粋します。

instance_variables
class Book
  def initialize(title, price)
    @title = title; @price = price
  end
end
 
book = Book.new("Programming Ruby", 2000)
p book.instance_variables  # [:@title, :@price]

これを利用して、jsonでメンバ変数を一括出力出来ます。

jsonでのメンバ変数の一括出力

以下を参考にさせていただきました。
http://stackoverflow.com/questions/4464050/ruby-objects-and-json-serialization-without-rails

jsonでの一括出力
def to_json
    hash = {}
    self.instance_variables.each do |var|
        hash[var] = self.instance_variable_get var
    end
    hash.to_json
end
jsonからの復元
def from_json! string
    JSON.load(string).each do |var, val|
        self.instance_variable_set var, val
    end
end

redisへの登録

あとは、上記のto_jsonを用いてredisに登録するだけですね。
簡単のため、redisはローカルホストでポートは変更していないこととします。
先ほどのBookクラスに上記のto_jsonが実装されているものとします。

redisへの登録
book = Book.new("Programming Ruby", 2000)

redis = Redis.new
redis.set "book" book.to_json
redisからの復元
redis = Redis.new
book_json = redis.get "book"

book = Book.new
book.from_json! book_json

puts book.title # Programming Ruby
puts book.price # 2000
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?