使用 Ruby Sinatra,@tasks.each 执行 |task|需要检查定义?(任务)

Using Ruby Sinatra, @tasks.each do |task| requires check for defined?(task)

我正在使用这个 tutorial 检查 Sinatra。在索引方法中,它选择所有任务:

@tasks = Task.all

在索引视图中,它迭代所有这些任务:

- @tasks.each do |task|

并且,在部分任务中,它显示名称:

= task.name

正如预期的那样,任务部分迭代了整个任务 class,但它继续执行最后一个任务并最终失败:

NameError - undefined local variable or method `task' for #<Sinatra::Application:0x4e0db18>:

这发生在每次迭代中,除非我测试是否定义了任务,即每个变量?

- if defined?(task)

这对我来说是出乎意料的。有人可以解释一下吗?

Main.rb:

# https://www.sitepoint.com/just-do-it-learn-sinatra-i/
require 'sinatra'
require 'slim'
require 'data_mapper'
require 'dm-sqlite-adapter'

DataMapper.setup(:default, ENV['DATABASE_URL'] || 'sqlite3:development.db')
class Task
  include DataMapper::Resource
  property :id,           Serial
  property :name,         String, :required => true
  property :completed_at, DateTime
end
DataMapper.finalize
DataMapper.auto_upgrade!

get '/' do
  @tasks = Task.all
  slim :index
end

post '/' do
  Task.create  params[:task]
  redirect to('/')
end

get '/:task' do
  @task = params[:task].split('-').join(' ').capitalize
  slim :task
end

delete '/task/:id' do
  Task.get(params[:id]).destroy
  redirect to('/')
end

put '/task/:id' do
  task = Task.get params[:id]
  task.completed_at = task.completed_at.nil? ? Time.now : nil
  task.save
  redirect to('/')
end

index.slim:

form action="/" method="POST"
  input type="text" name="task[name]"
  input.button type="submit" value="New Task >>"

h2 My Tasks

ul.tasks
  - @tasks.each do |task|
    - if defined?(task)
      == slim(:task, locals: { task: task })

task.slim:

li.task
  - if defined?(task)
    = task.name
    form.update action="/task/#{task.id}" method="POST"
      input type="hidden" name="_method" value="PUT"
      / Logic is bad here and will be fixed.
      - if task.completed_at.nil?
        input type="submit" value="  " title="Complete Task"
      - else
        input type="submit" value="✓" title="Uncomplete Task"
    form.delete action="/task/#{task.id}" method="POST"
      input type="hidden" name="_method" value="DELETE"
      input type="submit" value="&times;" title="Delete Task"

我恢复了代码并尝试重现问题以获得堆栈跟踪。它没有复发。我只能推测数据库中存在错误,导致它包含导致问题的无效条目。