# 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
然后浏览器访问: 可以获取刚才的内容。
日志会由原来的:
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
class HelloController < ActionController::Metal
include AbstractController::Rendering
include ActionView::Layouts
append_view_path "#{Rails.root}/app/views"
def index
render "hello/index"
end
end
加入 Redirection 模块
想使用重定向相关代码,你也需要引入它们:
class HelloController < ActionController::Metal
include ActionController::Redirecting
include Rails.application.routes.url_helpers
def index
redirect_to root_url
end
end
加入其它模块
参考 ActionController::Base 引入其它模块,以达到目的。
class ApiController < ActionController::Metal # 使用 Metal, 而不是 Base
include ActionController::Helpers
include ActionController::Redirecting
include ActionController::Rendering
include ActionController::Renderers::All
include ActionController::ConditionalGet
# 需要响应 .json .xml 等不同格式的话,使用它。
include ActionController::MimeResponds
include ActionController::RequestForgeryProtection
# 如果你需要 SSL
include ActionController::ForceSSL
include AbstractController::Callbacks
# 想要知道 Controller 处理过程中,性能这方面的数据。
include ActionController::Instrumentation
# 需要转换 params 类型的话,可以使用它。
include ActionController::ParamsWrapper
include Devise::Controllers::Helpers
# 在项目里使用路由相关的 helper 方法。
include Rails.application.routes.url_helpers
# 视图文件放在哪?
append_view_path "#{Rails.root}/app/views"
# 需要转换 params 类型的话,可以使用它。
# { "person": { "name": "Kelby", "email": "leekelby@gmail.com" }}
wrap_parameters format: [:json]
# 根据客户端决定是否需要。(另,如果客户端不是浏览器的话,它会自动跳过)
protect_from_forgery
end