Ruby On Rails 2.0.2源代码分析(3) resource
RESTful的化身----resource
当然,光把RESTful和resource扯到一起似乎相当狭义,在Rails中,ActionController::Resources抽象了REST中的Resource,这里,我不谈REST的相关概念,网上资料一大坨。我们就来看看Rails中是如何通过Resource来轻松,简便的完成RESTful应用的吧。
resources.rb
源代码路径:/actionpack-2.0.2/lib/action_controller/resources.rb
首先,我们也不需要将resource看得多么的高深,你可以把他理解为,当你在routes.rb中定义如下的resource的时候:
map.resources :products
Rails会自动为我们生成众多的named route,这些route通过http verb和相应的controller中的action对应起来,当然了,众多的helper方法也随即产生。如下表所示:
Named Route
Helpers
product
product_url, hash_for_product_url,
product_path, hash_for_product_path
new_product
new_product_url, hash_for_new_product_url,
new_product_path, hash_for_new_product_path
edit_product
edit_product_url, hash_for_edit_product_url,
edit_product_path, hash_for_edit_product_path
...
...
从这个角度来想,你可以把resource想成是众多相关named route的一个马甲。
整个流程比较的直观,Rails通过resource按部就班的完成各种route的生成,接下来我们看一看核心代码是如何完成这些功能的。首先,还是在routes.rb中,可能会定义如下的resource:
Ruby代码
ActionController::Routing::Routes.draw do |map|
map.resources :products
...
end
ActionController::Routing::Routes.draw do |map|
map.resources :products
...
end
resources方法定义在ActionController::Resources这个module中,然后通过mixin进入到Mapper类的。那我们首先来看一看这个方法:
Ruby代码
def resources(*entities, &block)
options = entities.extract_options!
entities.each { |entity| map_resource(entity, options.dup, &block) }
end
def resources(*entities, &block)
options =
相关文档:
可用库:getoptlong.rs, optionparser
对应类:GetoptLong, OptionParser
前者已过时,建议使用后者,且后者比前者易用。
后者特点:
1. 参数描述和代码处理写在一起
2. 输出参数说明,不需单独维护
3. 可选参数和命令参数描述简洁
4. 参数可自动转换为特定的类
5. ......
1.1.Rails
1.1 创建一个Rails应用程序
$ rails app_name
可选项:
-d, database=xxx 指定安装一个数据库(mysql oracle postgresql sqlite2 sqlite3 ), 默认情况下是数据库
-r, ruby-path= 指定Ruby的安装路径,如果没有指定,scripts使用env去找Ruby
-f, freeze (冻结)freezes Rails在vendor/rails目录
1.2 API Docume ......
开发环境:
Ruby:1.9.1
Rails:2.3.5
Rake:0.8.7
Rack:1.0.1
Mysql:5.0.9
Ruby-mysql:mysql-2.8.1-x86-mswin
IDE:RubyMine2.0.1
数据库准备:
database:dbdevelopment
user:crystal
password:crystal
一、创建Ruby项目RorTest
二、修改database.yml
这里只启用development环境数据库,修改配置文件如下:
dev ......
开发环境:
OS:Windows XP
Ruby:Ruby1.9.1
Rails:Rails2.3.5
will_paginate:will_paginate2.3.11
(在命令行中运行 gem install mislav-will_paginate --source http://gems.github.com )
IDE:Rubymine2.0.1
DB:mysql5.0.9
本例在上一个例子(Ruby实践—简单数据库操作)的基础上实现分页,利用的是will_p ......
下面介绍Ruby form的两种写法。
Ruby form写法一:使用form_for
< % form_for :order, :url => { :action => :save_order } do |form| %> < p> < %= label :order ......