101基本ruby / sinatra:未定义变量'session'

时间:2012-05-07 21:22:49

标签: ruby sinatra

app.rb:

require 'sinatra'

class MyApp < Sinatra::Application
    enable :sessions

    if session[:user_id].nil? then
        erb :login
    end
end

require_relative 'routes/init.rb'

config.ru:

require './app'
run MyApp

运行shotgun config.ruthin start -R config.ru会产生:

app.rb:3:in `<top (required)>': undefined local variable or method `session' for main:Object (NameError)

这非常101。是什么给了什么?

1 个答案:

答案 0 :(得分:2)

我认为问题在于您没有get块内的代码或类似内容。基本上,sinatra只会在请求的上下文中知道session对象。这样的东西适用于根URL:

require 'sinatra'

class MyApp < Sinatra::Application
  enable :sessions

  get '/' do
    if session[:user_id].nil? then
      erb :login
    end
  end
end