Last active
October 23, 2015 06:15
-
-
Save f440/413c4e6b5acb238e8b64 to your computer and use it in GitHub Desktop.
Redis で Edit & Undo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'redis' | |
# 初期化 | |
# edit = EditModel(12345) | |
# | |
# 編集 | |
# edit.commit(serialized_object) | |
# | |
# アンドゥ | |
# edit.move(-1) | |
# | |
# 任意の編集履歴に移動 | |
# edit.reset(10) | |
# | |
# 編集内容を表示 | |
# edit.show(10) | |
# | |
# 編集履歴(のID)一覧取得 | |
# edit.log | |
# | |
class EditModel | |
def initialize(object) | |
@object = object | |
end | |
def commit(json) | |
# 編集オブジェクト作成 | |
edit_id = redis.incr("edit_id") | |
redis.set("edit:#{edit_id}", json) | |
# 現在位置よりあとの編集履歴を削除 | |
(redis.lrange "undo:#{@object}", self.current + 1, -1).each do |e| | |
redis.del "edit:#{e}" | |
end | |
redis.ltrim "undo:#{@object}", 0, self.current | |
# 編集履歴に新しい編集オブジェクトを追加 | |
position = redis.rpush("undo:#{@object}", edit_id).to_i | |
# 現在位置を最新の編集オブジェクトの位置に移動 | |
self.current = position | |
end | |
# n: 絶対位置 | |
def reset(n) | |
self.current = n | |
end | |
# n: 相対位置 | |
def move(n) | |
self.current = current + n | |
end | |
def log | |
redis.lrange "undo:#{@object}", 0, -1 | |
end | |
def show(edit_id) | |
redis.lindex "undo:#{@object}", edit_id | |
end | |
private | |
def redis | |
@redis ||= Redis.new | |
end | |
def current | |
redis.get("current:#{@object}").to_i | |
end | |
def current=(n) | |
redis.set "current:#{@object}", n | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment