转储到yaml文件后为什么负值变为正值?

Xul*_*lnn 0 ruby yaml sinatra

我有一个简单的sinatra应用程序使用yaml文件来处理数据.其中一个特点是User可以投票或否决Question.投票功能很好,但在实施否决功能时我遇到了一些奇怪的事情.

简单地说:

  • 当问题的当前votes_count为正(>= 1)时,数字将正确减少
  • 但是当一个问题的当前votes_count值为零或负数时,该数字将在data散列中成功减少,但在转储data哈希进入yaml文件后,负数变为正数.

这是yaml文件Question:

'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
Run Code Online (Sandbox Code Playgroud)

这是与否决权功能相关的路由处理程序:

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
Run Code Online (Sandbox Code Playgroud)

这是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
Run Code Online (Sandbox Code Playgroud)

如果我update在更新data哈希之前和之后暂停程序内部的方法,它会显示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},
Run Code Online (Sandbox Code Playgroud)

后:

[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},
Run Code Online (Sandbox Code Playgroud)

哈希中的键"votes_count"data值是-1在更新之后,但在我将data哈希转储到yaml文件之后,yaml文件"votes_count"中的用户的值变为1.如果hash中的值是-2,它将成为2yaml文件.

我尝试在irb中创建一个负值的哈希值,然后将其转储到yaml文件中,一切正常.我不知道发生了什么.有人能帮助我吗?

mec*_*cov 5

它看起来就像问题一样

f.write(Psych.dump(data).delete("---"))
Run Code Online (Sandbox Code Playgroud)

你删除-.

例如

"-1".delete("---") #=> "1"
Run Code Online (Sandbox Code Playgroud)