Metal 使用举例
原生的 Metal
在 Rails 里 metal 也属于 middleware,我们可以这么用:
# config/routes.rb
get 'hello' => 'hello#index'
# ...# app/controllers/hello_controller.rb
class HelloController < ActionController::Metal
def index
self.response_body = "Hello World!"
end
end然后浏览器访问:http://localhost:3000/hello 可以获取刚才的内容。
日志会由原来的:
Started GET "/hello" for 127.0.0.1 at 2014-04-27 09:04:49 +0800
Processing by HelloController#index as HTML
Completed 200 OK in 1ms (ActiveRecord: 0.0ms)变为:
Started GET "/hello" for 127.0.0.1 at 2014-04-27 08:57:07 +0800加入 Rendering 模块
默认 ActionController::Metal 是没有提供渲染视图、模板和其它需要明确调用到 response_body=, content_type=, status= 等方法。如果你需要这些,可以引入它们:
加入 Redirection 模块
想使用重定向相关代码,你也需要引入它们:
加入其它模块
参考 ActionController::Base 引入其它模块,以达到目的。
上述代码,仅供参考。关于各模块及其作用,详情可以参考对应章节。
参考
最后更新于
这有帮助吗?