rails源码分析之Controller
2014-01-08 10:43
309 查看
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
app,交由rack层进行处理,再传递给web服务器生成相应的结果,通过浏览器返回给用户。
这个例子中对应mvc,只有Controller没有view。如果要通过view来定制内容需要引入ActionController::Rendering模块,来引入对应的功能。
ActionController::Base继承于Metal,主要是引入如上述例子ActionController::Rendering,ActionController::Redirecting的功能模块方法方便后继使用,你也可以根据项目实际情况通过without_modules类方法,去掉相关的方法。
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 endrails充分利用了ruby的动态性,体现了面向对象的组合与扩展特性,需要什么样的功能引入什么样的功能模块(方法),扩展性强,体现了面向对象中的组合(组合优于继承)。
ActionController::Base继承于Metal,主要是引入如上述例子ActionController::Rendering,ActionController::Redirecting的功能模块方法方便后继使用,你也可以根据项目实际情况通过without_modules类方法,去掉相关的方法。
相关文章推荐
- py2exe使用方法 (含一些调试技巧,如压缩email 类)(转)
- 解决 Agent admitted failure to sign using the key 问题 with ssh
- 进程控制之wait3和wait4函数
- AIR 中 如何利用titleIc…
- 进程控制之waitid函数
- Failed to fetch URL http://dl.htcdev.com/sdk/addon.xml, reason: peer not authenticated
- Column \'表名.某列名\' is invalid in the select list because it is not contained in either an aggregate f
- Column \'表名.某列名\' is invalid in the select list because it is not contained in either an aggregate f
- There is no source code available for the current location
- There is no source code available for the current location
- 进程控制之wait和waitpid函数
- 向优秀的效率类应用学习--邮件客户端(Mailbox、Swizzle以及Dispatch)
- http://blog.csdn.net/leshami/article/details/5542983
- hdu 4819 Mosaic
- 胖虎白话学习设计模式之责任链设计模式(Chain of Responsibility)
- Leetcode: Climbing Stairs
- cairo简单学习
- LeetCode Climbing Stairs
- Pre-Compositing Textures for Terrain Rendering
- saiku查询出错如何debug(saiku查询过程的本质),以及相关workbench的schema设置