Ruby/tk 設定の保存

設定情報クラスのシリアライズとデシリアライズについて、メモ。
ちなみに、参考の「example04.rb」がうまくできなかった。
設定ファイル代わりに使えそう。

このままでは使いづらいのでmoduleにしないと。

参考[るびま]
http://jp.rubyist.net/magazine/?0010-YAML


require 'tk'
require 'yaml'

class Info
attr_accessor :path
def initialize
@path = nil
end
end

class Demo
def initialize
@yaml_file="info.yaml"
if File.exist?(@yaml_file)
@info = YAML.load_file(@yaml_file)
begin
raise "error" unless @info.path
rescue
@info = Info.new()
end
else
@info = Info.new()
end
end

def getpath
@info.path = Dir.pwd unless @info.path
file = Tk.getOpenFile(:initialdir=>@info.path)
unless file == ""
@info.path = File.dirname(file)
end
end

def runing
TkButton.new(nil, :text=>:openfile,:command=>proc{getpath}).pack
Tk.mainloop
finalize()
end

def finalize
yaml = YAML.dump(@info)
open(@yaml_file, "w"){|file|
yaml.each{|line|
file << line
}
}
end
end

demo = Demo.new()
demo.runing