【发布时间】:2014-08-26 23:30:06
【问题描述】:
我正在使用以下内容尝试写入 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
该插件会因 []= 未定义而出错,或者将退出而没有任何错误或任何操作。
也有人说要使用block类型的write,我试过了,但还是不行。
get_netnote 有效,其余无效,我似乎无法弄清楚原因。
【问题讨论】:
-
File.write(@file, @data.to_yaml)是如何写入文件。你有像$notedb和$netnotedb这样的全局变量。如果您使用全局变量来解决变量范围问题,请不要这样做,因为那是代码异味。 -
好吧,我认为它应该放在哪里,还有其他东西可以使这个工作吗?我不太擅长 ruby 和 yaml 编写
-
现在可以使用了,感谢帮助
-
你自私地告诉我们“它正在工作”但没有发布答案。如果您解决了问题,您应该发布解决方案并将其标记为已接受以“关闭”此问题。不要将
<closed>等自己的标签放在标题中。 -
抱歉,我不能接受自己的回答(至少在 2 天内),如果您愿意,我将不胜感激。