Sinatra 似乎期望 class 应该成为当前框架的一部分
Sinatra seemingly expecting that class should be a part of current framework
我正在使用 Sinatra,并使用以下代码进行设置:
require 'sinatra/base'
class MyServer < Sinatra::Base
def initialize()
puts 'initialize'
super(app)
@my_thing = Something.new
end
run! if app_file == [=11=]
end
class Something
def initialize
@a_thing
end
end
当我 运行 ruby test.rb
时,我得到这个错误:
Unexpected error while processing request: uninitialized constant MyServer::Something
这表明它期望 Something 成为 MyServer 域中的 class(我最近才开始 Ruby,所以不知道正确的术语)。将 Something
class 移动到 MyServer
class 内部,它起作用了。
这对于写在这个文件中的 class 没问题,但我想从相关文件中添加一个 class 作为 属性。我试过将 require_relative
语句移动到 class 内部,但没有奏效。
有什么方法可以告诉它这不是当前框架的一部分,或者我应该以另一种方式处理这种情况?
当您调用 run!
时,服务器立即启动,脚本的其余部分仅在服务器完成时才执行。当您在脚本中调用 run!
时,Something
class 尚未定义,因此对服务器不可用。
该行不一定需要在 MyServer
class 内,您可以将其移动到文件末尾,但您需要指定接收者:
require 'sinatra/base'
class MyServer < Sinatra::Base
# Define your app...
end
# Your helper object...
class Something
#...
end
# Now start the server as the last thing:
MyServer.run! if MyServer.app_file == [=10=]
Sinatra 本身 uses an at_exit
block to start the server 处于 classic 模式,因此服务器仅在加载所有内容后启动。
我正在使用 Sinatra,并使用以下代码进行设置:
require 'sinatra/base'
class MyServer < Sinatra::Base
def initialize()
puts 'initialize'
super(app)
@my_thing = Something.new
end
run! if app_file == [=11=]
end
class Something
def initialize
@a_thing
end
end
当我 运行 ruby test.rb
时,我得到这个错误:
Unexpected error while processing request: uninitialized constant MyServer::Something
这表明它期望 Something 成为 MyServer 域中的 class(我最近才开始 Ruby,所以不知道正确的术语)。将 Something
class 移动到 MyServer
class 内部,它起作用了。
这对于写在这个文件中的 class 没问题,但我想从相关文件中添加一个 class 作为 属性。我试过将 require_relative
语句移动到 class 内部,但没有奏效。
有什么方法可以告诉它这不是当前框架的一部分,或者我应该以另一种方式处理这种情况?
当您调用 run!
时,服务器立即启动,脚本的其余部分仅在服务器完成时才执行。当您在脚本中调用 run!
时,Something
class 尚未定义,因此对服务器不可用。
该行不一定需要在 MyServer
class 内,您可以将其移动到文件末尾,但您需要指定接收者:
require 'sinatra/base'
class MyServer < Sinatra::Base
# Define your app...
end
# Your helper object...
class Something
#...
end
# Now start the server as the last thing:
MyServer.run! if MyServer.app_file == [=10=]
Sinatra 本身 uses an at_exit
block to start the server 处于 classic 模式,因此服务器仅在加载所有内容后启动。