我正在学习 Sinatra,并试图让我的大脑围绕 Sinatra::Base
进行。 documentation不轻易回答问题:
Sinatra::Base
负责什么?
有没有简单的思考方法? (即也许有一个很好的图表或其他东西?)
或者答案只是一长串功能? (例如:“Sinatra::Base
负责错误、过滤器、路由、模板等”)
或者是一些简单的东西,比如:“Sinatra::Base
是 Sinatra,减去执行上下文,Sinatra::Application
”?
最佳答案
Sinatra::Base
是没有委托(delegate)的 Sinatra。考虑以下带有委托(delegate)的代码:
# app.rb
require 'sinatra'
get '/' do
render :template
end
这种风格免费为您提供选项解析器:
$ ruby app.rb -h
Usage: app [options]
-p port set the port (default is 4567)
-o addr set the host (default is localhost)
-e env set the environment (default is development)
-s server specify rack server/handler (default is thin)
-x turn on the mutex lock (default is off)
当您使用应用程序运行脚本时,它还会使用适当的 Rack 处理程序启动服务器,因此您无需编写任何相关代码。
它之所以有效,是因为 Object
在 sinatra/main
中用 Sinatra::Delegator
进行了扩展。请参阅 http://git.io/zWl7RA 和 http://git.io/NxgpBg 。它将所有 Sinatra DSL 方法委托(delegate)给 Sinatra::Base
的预配置实例,即 Sinatra::Application
。
当您以模块化风格编写应用程序时,不会委托(delegate)任何内容。您只需继承基础:
require 'sinatra/base'
class Application < Sinatra::Base
get '/'
render :template
end
end
Application.run!
因此,Sinatra::Base
目前负责在 Rack、Tilt 和其他依赖项之上实现所有 Sinatra DSL 方法。
关于sinatra - Sinatra::Base 负责什么? (即类(class)概述),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24876786/