顶层代码将委托给Sinatra::Application
,因此这将是运行经典应用程序的场景:
# app.rb
require 'sinatra'
get '/' do
'hi'
end
# config.ru
require './app'
run Sinatra::Application
如果你定义一个模块化应用程序,你会像这样运行它:
# app.rb
require 'sinatra/base'
class Kincalc < Sinatra::Base
get '/' do
'hi'
end
end
# config.ru
require './app'
run Kincalc
现在我假设你想要做的是:
# otherfilename.rb
require 'sinatra'
get '/' do
'hi'
end
# app.rb
require 'sinatra/base'
class Kincalc < Sinatra::Base
require './otherfilename'
end
# config.ru
require './app'
run Kincalc # Sinatra::Application seems to work
您遇到的行为(获取 404 File Not Found)实际上是正确的,因为require
不关心它被调用的词法范围。查看以下示例
# a.rb
puts "in a, top level: #{self.inspect}"
module Example
puts "in a, nested: #{self.inspect}"
require 'b'
end
# b.rb
puts "in b: #{self.inspect}"
结果输出应该是:
in a, top level: main
in a, nested: Example
in b: main
因此,如果您想使用一个模块化应用程序,您应该执行以下操作:
# otherfilename.rb
Kincalc.get '/' do
'hi'
end
或再次打开课程:
# otherfilename.rb
class Kincalc
get '/' do
'hi'
end
end
或者您实际上otherfilename.rb
可以Sinatra::Application
在Kincalc
.
# app.rb
require 'sinatra/base'
require './otherfilename'
class Kincalc < Sinatra::Base
use Sinatra::Application
end
或者您可以更改将顶级 DSL 方法委托给的位置:
# app.rb
require 'sinatra/base'
class Kincalc < Sinatra::Base
Sinatra::Delegator.target = self
require './otherfilename'
end