【发布时间】:2019-07-16 05:30:52
【问题描述】:
我有一个简单的 sinatra 应用程序,它使用 yaml 文件来处理数据。其中一项功能是User 可以投票或否决Question。投票功能运行良好,但我在实现否决功能时遇到了一些奇怪的事情。
简单地说:
- 当问题的当前
votes_count为正数 (>= 1) 时,数字将正确减少 - 但是当问题的当前
votes_count为零或负数时,data哈希中的数字会成功减少,但是在将data哈希转储到yaml文件后,负数变为正数。
这是Question的yaml文件:
'1': !ruby/hash:Sinatra::IndifferentHash
title: " Best way to require all files from a directory in ruby?"
description: What's the best way to require all files from a directory in ruby ?
user_id: '3'
votes_count: 0
# other user information
这是与否决功能相关的路由处理程序:
post "/questions/:id/veto" do
check_vote_validity_for_question(params[:id])
@question = Question.find_by(:id, params[:id])
@question.votes_count = (@question.votes_count.to_i - 1)
Question.update(params[:id], votes_count: @question.votes_count )
# omit user related code
end
这是update 方法:
def self.update(id, attrs)
data = load_data_of(data_name)
# binding.pry
obj_info = data[id]
attrs.each do |k, v|
v = v.to_s if v.is_a?(Array)
obj_info[k] = v
end
# binding.pry
File.open(File.join(data_path, "#{data_name.to_s}.yaml"), "w+") do |f|
f.write(Psych.dump(data).delete("---"))
end
end
如果我在更新data 哈希之前和之后暂停update 方法内的程序,则表明votes_count 的值设置正确。
之前:
[1] pry(Question)> data
=> {"1"=>
{"title"=>" Best way to require all files from a directory in ruby?",
"description"=>"What's the best way to require all files from a directory in ruby ?",
"user_id"=>"3",
"votes_count"=>0},
之后:
[1] pry(Question)> data
=> {"1"=>
{"title"=>" Best way to require all files from a directory in ruby?",
"description"=>"What's the best way to require all files from a directory in ruby ?",
"user_id"=>"3",
"votes_count"=>-1},
更新后data hash中key"votes_count"的值为-1,但是我将data hash转储到yaml文件后,yaml文件中用户的"votes_count"的值变成了1。而如果hash中的值为-2,在yaml文件中会变成2。
我尝试在 irb 中创建一个具有负值的哈希,然后将其转储到 yaml 文件中,一切正常。我不知道发生了什么。有人可以帮助我吗?
【问题讨论】:
-
"它变成了
1",它指的是什么?这是否意味着您在句子片段中指示的哈希成为一个?还是votes_count的值?还是把键votes_count改成数字1?或者 YAML 文件包含1作为键vote_count的值?在你的代码"votes_count"中没有一个值是一个值,它是一个键。请编辑您的问题,使其不那么含糊。 -
@Anthon,我编辑了这个问题。如果我有一个像
h = { "a" => -2 }这样的哈希,那么在我将h转储到一个yaml 文件之后,yaml 文件中的内容就变成了a: 2