我正在使用以下内容尝试写入yaml文件
class NoteDB
attr_reader :data
def initialize(file)
@file = file
if File.exists?(@file)
@data = YAML.load_file(@file)
else
puts "Warning: note db #{@file} does not exist. Skipping loading."
@data = Hash.new
end
end
def data=(newdata)
@data = newdata
#f = File.open(@file, 'w')
#YAML.dump(@data, f)
File.write(@file, @data.to_yaml)
#f.close
end
end
下一位是每个命令的设置方法
class NotePlugin
include Cinch::Plugin
def set_netnote(m, network, note)
return unless m.channel == "#channel"
data = $netnotedb.data
network.downcase!
data[network] = note
m.reply "Note for #{network} has been set."
$netnotedb.data = data
end
def add_cat(m, category)
return unless m.channel == "#channel"
category.downcase!
data = $notedb.data
if data.has_key? category
m.reply "#{Format(:bold, "Error:")} Category "#{category}" exists."
else
data[category] = Array.new
$notedb.data = data
m.reply "Category "#{category}" added."
end
end
def del_cat(m, category)
return unless m.channel == "#channel"
category.downcase!
data = $notedb.data
if data.has_key? category
data.delete category
$notedb.data = data
m.reply "Category "#{category}" removed."
else
m.reply "#{Format(:bold, "Error:")} Category "#{category}" does not exist."
end
end
def add_item(m, cat, item)
return unless m.channel == "#channel"
cat.downcase!
data = $notedb.data
if data.has_key? cat
data[cat] << item
$notedb.data = data
m.reply "Item added."
else
m.reply "#{Format(:bold, "Error:")} Category "#{cat}" does not exist."
end
end
def del_item(m, cat, index)
return unless m.channel == "#channel"
cat.downcase!
index = index.to_i - 1
data = $notedb.data
if data.has_key? cat
if data[cat][index].nil?
m.reply "#{Format(:bold, "Error:")} Item ##{index + 1} not found."
else
data[cat].delete data[cat][index]
$notedb.data = data
m.reply "Deleted item ##{index + 1}."
end
else
m.reply "#{Format(:bold, "Error:")} Category "#{cat}" does not exist."
end
end
end
插件要么会在[]=未定义的情况下出错,要么会在没有任何错误或操作的情况下退出。
有人还说要使用块类型的写入,我试过了,但似乎仍然无法实现。
get_netnote有效,其余的无效,我似乎不明白为什么。
class NoteDB
attr_reader :data
def initialize(file)
@file = file
if File.exists?(@file)
@data = YAML.load_file(@file)
else
puts "Warning: note db #{@file} does not exist. Skipping loading."
@data = Hash.new
end
end
def data=(newdata)
@data = newdata
#f = File.open(@file, 'w')
#File.write(@file, @data.to_yaml)
File.open(@file,'w') do |f|
f.write YAML.dump(@file) + @data.to_yaml
end
end
end
f.write YAML.dump(@file) + @data.to_yaml
是其中的关键,其中@file是您的yaml文件的装饰器/变量,转储您的文件,用@data将其添加到yaml中,然后编写它。