为什么控制器?

Why controllers?

我花了很多时间在 sinatra 上进行开发,这对我来说效果很好,因为我只在小项目上工作过,规模不是问题。现在我有使用rails的需要,结构让我有点困惑。我知道当我输入 localhost:3000/images rails 在 routes.rb 中寻找路线(例如 get 'images#index'),然后进入控制器 images 然后在图像中寻找index 函数,最后找到 index 视图并渲染它。

为什么需要进行所有这些更改?它不能像 sinatra 那样更简单(它似乎只在主文件中包含控制器步骤)吗?在一个答案中,我正在寻找为什么最好按照 rails 的方式来做,包括具体原因、优点和缺点以及示例。

提前致谢!

Konstantin Haase 是 Sinatra 的当前维护者,感觉他们都适合不同类型的应用程序:

They are both solving a different set of issues, even though they indeed overlap. While Rails is a framework focused on writing model driven web applications, Sinatra is a library for dealing with HTTP from the server side. If you think in terms of HTTP requests/responses, Sinatra is the ideal tool. If you need full integration and as much boilerplate as possible, Rails is the way to go.

David Heinemeier Hansson 也认为两者都有空间,但感觉应用的大小应该会影响使用哪一个:

Sinatra is great for the micro-style, Rails is not. As long as you stay micro, Sinatra will beat Rails. If you go beyond micro, Rails will beat Sinatra.

所以,基本上,Sinatra 和 Rails 是不同的,它们有不同的用例。 Rails 是一个开源的全栈网络应用程序框架。它遵循流行的 MVC 框架(模型、视图、控制器) 模型,并以其“约定优于配置”应用程序开发方法而闻名。因此,如您所见,controller 是 Rails 的一部分。

您可以找到许多描述 Rails 和 Sinatra 之间差异及其用例的文章。这里有几个有趣的博客:

Rails vs. Sinatra

Rails vs. Sinatra by Example

K M Rakibul Islam 的回答很棒。您也可以查看 Rack。 Rails 和 Sinatra 都是基于它构建的。 Rack 是一个 Web 服务器接口,它期望 "app" 是 Ruby object,它通过名为 call 的方法获取请求散列,然后用包含的数组进行响应http 响应代码、http headers 和响应 body。这是很准系统。查看 Rack 可能会让您更好地了解两者之间的差异——如果您对 "how" 而不是 "why".

感兴趣