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 =
相关文档:
self上下文
Ruby的self有和Java的this相似之处,但又大不相同。Java的方法都是在实例方法中引用,所以this一般都是指向当前对象的。而Ruby的代码逐行执行,所以在不同的上下文(context)self就有了不同的含义,先来看看常见的context self都代表哪些
1
2
3
4
5
6
7
8
9
10
11
12
13
......
class Point
@x = 1
@y = 2
def initialize(x,y)
@x,@y = x,y
end
end
代码中的@x,@y为实例变量,实例变量只对self的环境起作用,因此initialize外面的@x=1,@y=2只对类本身起作用,而方法内部,的@x,@y是对对象的实例起作用的。
class Point
include Enumerable
def initialize(x ......
我们知道ruby中对于整数的[],[]=,<<,>>操作是针对于二进制的值来运算的。
我现在写一个针对十进制数操作的类,拥有整数的所有方法,如下:
class InterEx
def initialize(val=0)
@val=val
end
def to_s
@val.to_s
end
def [](idx)
self.to_s[idx].to_i
end
d ......
开发环境:
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 ......