contoller的继承关系为AbstractController::Base<ActionController::Metal<ActionController::Base<ApplicationController<用户定义Controller。
AbstractController::Base提供Controller的一个抽象基类,不能被直接使用,只能被继承,只是提供一些基本的方法和属性,等价于如c#,java的Abstract类 ,他没有涉及web,http的相关处理,或者可以说和rack无关。ActionController::Metal继承于AbstractController::Base提供了关于Rack的接口,将他变成了一个可以被执行的rack app。
下面举一个简单的例子,首先定义一个Controller
class HelloController < ActionController::Metal
def index
self.response_body = "Hello World!"
end
end
然后在config/routes.rb中添加路由
match 'hello', :to => HelloController.action(:index)
这样就可以通过在浏览器输入对应url,获取一个显示hello word的页面的输出。实际过程可以简单描述是传递一个web请求给router,由router做相应转发(dispatch),转发到相关的action,由他生成了一个Rack
app,交由rack层进行处理,再传递给web服务器生成相应的结果,通过浏览器返回给用户。
这个例子中对应mvc,只有Controller没有view。如果要通过view来定制内容需要引入ActionController::Rendering模块,来引入对应的功能。
class HelloController < ActionController::Metal
include ActionController::Rendering
append_view_path "#{Rails.root}/app/views"
def index
render "hello/index"
end
end
同样要获取重定向功能,可以引入对应的功能模块(方法)
class HelloController < ActionController::Metal
include ActionController::Redirecting
include Rails.application.routes.url_helpers
def index
redirect_to root_url
end
end
rails充分利用了ruby的动态性,体现了面向对象的组合与扩展特性,需要什么样的功能引入什么样的功能模块(方法),扩展性强,体现了面向对象中的组合(组合优于继承)。ActionController::Base继承于Metal,主要是引入如上述例子ActionController::Rendering,ActionController::Redirecting的功能模块方法方便后继使用,你也可以根据项目实际情况通过without_modules类方法,去掉相关的方法。