我怎样才能让 ruby 代码和 sequel 在 sinatra 中工作?

How can I get this ruby code with sequel to work in sinatra?

我试图只允许一个人查看该页面,前提是他们的名字在数据库中。我想最好的办法是遍历所有条目并检查它是否匹配,如果匹配则显示它并停止循环。我一直收到空白页,有什么帮助吗?

get '/' do
  user  = "john"
  num = DB[:users].all

  for person in num  do
    if person[:name].to_s == user then
      File.read('index.html')
      break
    else 
      "you're not authorized"
    end
  end

end

如果我要删除 if 语句中的 break 行,我会收到此错误:

  NoMethodError at /
  undefined method `bytesize' for #<Hash:0x007fcf60970a68>
  file: utils.rb location: bytesize line: 369

问题是 for 循环的计算结果为 nil(除非你 break 并向 break 提供一个值),所以你的块是 returning nil,所以没有什么可渲染的。

但真正的问题是 for 是这里的错误解决方案。您要做的是检查数组 DB[:users].all 是否包含其 :name 成员等于 user 的哈希。您可以为此使用循环,但除了 for 在惯用的 Ruby 代码中很少见(首选 Enumerable#each )之外,它还会使代码的意图更难理解。相反,您可以像这样使用 Enumerable#find(Array class 包含 Enumerable 模块中的方法):

get '/' do
  username = "john"
  users = DB[:users].all

  matching_user = users.find do |user|
    user[:name] == user
  end

  if matching_user
    return File.read('index.html')
  end

  "you're not authorized"
end

...但是由于您实际上并不关心匹配的用户 - 您只关心匹配的用户 是否存在 - 使用 [=32= 会更清楚], 即 returns truefalse:

get '/' do
  username = "john"
  users = DB[:users].all

  if users.any? {|user| user[:name] == user }
    return File.read('index.html')
  end

  "you're not authorized"
end

编辑: 正如@user846250 指出的那样,最好让数据库来检查是否存在任何匹配的用户。像这样:

get '/' do
  username = "john"

  if DB[:users].where(:name => username).empty?
    return "you're not authorized"
  end

  File.read('index.html')
end

这是更可取的,因为当您实际上并不关心任何数据库中的数据时,而不是将所有记录从数据库加载到 Ruby(这是 DB[:users].all 会做的)其中——Sequel 将只询问数据库是否有任何匹配的记录,然后 return truefalse.