Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! ruby -Ks
- # -*- coding: Shift_JIS -*-
- #Memento / あの頃に戻りたい
- #メメントのメメは女々しいのメメです。
- #スナップショット作るなりして、後々戻せるようにする機能を指すっぽいです。
- #エディタのundo/redoが分かりやすいんじゃなかろうか
- #MementoもハッシュやStructで済む気がする・・・簡略簡略
- class Editor
- Buffer = Struct.new(:text, :font_size, :font_type) #簡単だけど、これがMemento
- def initialize
- @text = ''
- @font_size = 10
- @font_type = '明朝'
- @buffers = []
- end
- attr_reader :text, :font_size, :font_type
- def view
- puts "(#{@font_type}で#{@font_size}ぐらいの表示がされていると考えます)", @text, '---------Separator----------'
- end
- def write(string)
- snapshot #操作する人が手動で呼び出すって考えもあるけど、今回は自動呼び出しさせます。
- @text += string
- end
- def undo(count=1)
- count *= -1
- @text, @font_size, @font_type = @buffers[count].text, @buffers[count].font_size, @buffers[count].font_type
- end
- def change_font(size, type=nil)
- snapshot
- @font_size = size
- @font_type = type if type
- end
- private
- def snapshot
- @buffers << Buffer.new(@text, @font_size, @font_type)
- end
- end
- editor = Editor.new
- editor.write "そういえば、株価めっちゃ落ちてますよね\n"
- editor.view
- editor.change_font 99, 'ゴシック'
- editor.write "もーもーもー\nマジであの頃に帰りたい・・・"
- editor.view
- editor.undo 2
- editor.view
- # 意図しないBuffer破壊メソッドを作ってしまわないよう気をつけるべきでしょう(戻せなくなる!)
- # ※もし本当にこういうのを作るんであれば、各メソッドの返り値はselfにしてメソッドチェーン出来るようにしておいたほうがいいと思う
Add Comment
Please, Sign In to add comment