10 月 23 - 25 日,QCon 上海站即将召开,现在购票,享9折优惠 了解详情
写点什么

Rails: 用 Resource_controller 插件给 Controllers 减肥

  • 2008-02-04
  • 本文字数:2561 字

    阅读完需:约 8 分钟

许多Rails大师提倡的一个导向原则是“丰满的模型,精瘦的控制器”。 Rails 控制器只应该包含一些在模型和视图之间周转用的代码。事务逻辑属于模型,而不属于控制器或视图。在如今支持 REST的 Rails 2.0 中,控制器变得非常相象,都包括七个基本的动作(索引、获取、创建、更新、删除、新增和编辑),且具有非常相似的实现方式。在 Rails 2.0 中,可以简单地用 script/generate scaffold standard 来建立控制器框架,即生成了一段具有 REST 特性的控制器代码,如下所示:

class StandardsController < ApplicationController

GET /standards

GET /standards.xml

def index
@standards = Standard.find(:all) respond_to do <span>|</span>format<span>|</span>

format.html # index.html.erb
format.xml { render :xml => @standards }
end
end # GET /standards/1

GET /standards/1.xml

def show
@standard = Standard.find(params[:id]) respond_to do <span>|</span>format<span>|</span>

format.html # show.html.erb
format.xml { render :xml => @standard }
end
end # GET /standards/new

GET /standards/new.xml

def new
@standard = Standard.new respond_to do <span>|</span>format<span>|</span>

format.html # new.html.erb
format.xml { render :xml => @standard }
end
end # GET /standards/1/edit

def edit
@standard = Standard.find(params[:id])
end # POST /standards

POST /standards.xml

def create
@standard = Standard.new(params[:standard]) respond_to do <span>|</span>format<span>|</span>

if @standard.save
flash[:notice] = ‘Standard was successfully created.’
format.html { redirect_to(@standard) }
format.xml { render :xml => @standard, :status => :created, :location => @standard }
else
format.html { render :action => “new” }
format.xml { render :xml => @standard.errors, :status => :unprocessable_entity }
end
end
end # PUT /standards/1

PUT /standards/1.xml

def update
@standard = Standard.find(params[:id]) respond_to do <span>|</span>format<span>|</span>

if @standard.update_attributes(params[:standard])
flash[:notice] = ‘Standard was successfully updated.’
format.html { redirect_to(@standard) }
format.xml { head :ok }
else
format.html { render :action => “edit” }
format.xml { render :xml => @standard.errors, :status => :unprocessable_entity }
end
end
end # DELETE /standards/1

DELETE /standards/1.xml

def destroy
@standard = Standard.find(params[:id])
@standard.destroy respond_to do <span>|</span>format<span>|</span>

format.html { redirect_to(standards_url) }
format.xml { head :ok }
end
end
end

除了特别的名字以外,所有自动生成的控制器代码都是这样的。

使用自动生成的控制器非常简单。在许多情况下,很少或者不需要对生成的代码做任何改变,尤其是当你把“精瘦的控制器”这个理念铭记于心时。

另一方面,Ruby/Rails 还有一条理念,就是 “不要重复自己(DRY)”。 如果存在几乎重复的代码,即便不是你自己写的,也是违背DRY 原则的。

输入: resource_controller。James Golick 贡献了一个新的 rails 插件,称为 resource_controller ,它可以实现与上面同样的控制器,代码如下:

class StandardsController < ApplicationController<br></br>resource_controller<br></br>end然而,这里仍有一个小小的瑕疵。 它没有提供标准的 xml 响应能力,但可以用一小段代码来实现:

class StandardsController < ApplicationController
resource_controller index.wants.xml { render :xml => @standards }

[new, show].each do <span>|</span>action<span>|</span>
action.wants.xml { render :xml => @standard })
end
create.wants.xml { render :xml => @standard, :status => :created, :location => @standard }
[update, destroy].each do <span>|</span>action<span>|</span>
action.wants.xml { head :ok }
end
[create_fails, update_fails].each do <span>|</span>action<span>|</span>
action.wants.xml { render :xml => @standard.errors, :status => :unprocessable_entity }
end
end

有了这个插件,写控制器代码如同写模型代码一样,只需加上像resource_controller这样的声明的类方法,以及action.wants之类的“回调”。这个插件自动为控制器的每个方法分配实例变量。在上面的代码中,给 index 方法分配了 @standards ,给其他方法分配了 @standard。

Rails 有一些公用的模式强迫改变控制器代码。其中包括嵌套资源。很容易在 config/routes.rb 中设置路由:

map.resources :organization, :has_many => :standards但是,一旦你这样做了,你就需要更改控制器来获取和使用上层资源,并在每个动作中正确使用。resource_controller 插件简化了这些。在如上面那样更改路由后,你只需添加一个声明来调用我们的控制器:

class StandardsController < ApplicationController<br></br>resource_controller<br></br>belongs_to :organization<br></br>endbelongs_to 声明允许嵌套资源使用控制器。现在,当一个控制器动作通过嵌套资源 URL 被访问时,例如 /organization/1234 /standards,控制器会自动创建一个名为 @organization 的实例变量,适当地设置好,并使用 standards 所关联地父对象来查找和 建立 Standard 模型的实例。

注意, 同样的控制器也工作在非嵌套的 URL 下,因此我们可以在 routes.rb 中做另一个映射,来允许在 organization 之外访问 starnards:

map.resources :standard<br></br>map.resources :organization, :has_many :standards这样 resource 控制器就会自动地工作在这两种上下文中了。

这个插件也处理命名空间控制器、多态嵌套资源(与 ActiveRecord 多态关联相似和相关)和其他一些奇妙地东西。你也可以获得 URL 以及工作在请求的 URL 上下文中的路径辅助函数。

看来 Resource_controller 是个有用的插件,毫无疑问随着它的成熟,会变得越来越好。细节见 James Golicks 的博客。另外还有 Fabio Akita 制作的一段屏幕录像,演示了这个插件的实际使用情况。

查看英文原文: Rails: Resource_controller Plugin Puts Controllers on a Diet

2008-02-04 20:591561
用户头像

发布了 33 篇内容, 共 64773 次阅读, 收获喜欢 0 次。

关注

评论

发布
暂无评论
发现更多内容

Vulkan-性能及精细化

江湖修行

android OpenGL ES opengl 渲染 vulkan

[国产化-银河麒麟v10桌面版]FTP适配(FtpClient)

alexgaoyh

Java web 麒麟操作系统 ftp服务 FtpClient commons.net

户外LED显示屏如何设计散热?

Dylan

设计 环境 LED显示屏 户外LED显示屏 led显示屏厂家

大咖云集︱2023第二届中国PMO&PM大会倒计时15天!

新消费日报

C语言驱动开发之内核解锁与强删文件

芯动大师

springboot+activiti+vue+mysql轻松搞定审批!(源码)

金陵老街

cilium 原理之sock_connect

沃趣科技

数据库 云计算 ebpf cilium 沃趣科技

鲲鹏助力清华大学夺取SolverChallenge2023竞赛冠军

彭飞

SpringBoot3文件管理

Java 架构 springboot SpringBoot3

从零开始,快速掌握VPS服务器的使用技巧与窍门!

一只扑棱蛾子

VPS VPS服务器

13. Python的文件操作

茶桁

Python 文件操作

go-zero 是如何实现计数器限流的?

AlwaysBeta

Go 微服务 限流算法 go-zero 限流器

微软为AI投了多少钱?以及是否要担心这笔疯狂的资本支出

B Impact

火山引擎DataTester:AB实验平台未来演进趋势是怎样的?

字节跳动数据平台

大数据 AB实验 对比试验 企业号 8 月 PK 榜 数字化增长

火山引擎VeDI助力零售品牌私域运营 实现与会员高效“沟通”

字节跳动数据平台

大数据 云服务 数据平台 火山引擎 企业号 8 月 PK 榜

条条大路通罗马系列—— 使用 Hiredis-cluster 连接 Amazon ElastiCache for Redis 集群

亚马逊云科技 (Amazon Web Services)

Amazon

go-zero 是如何做路由管理的?

AlwaysBeta

Go 源码 微服务 go-zero 路由

Programming abstractions in C阅读笔记:p88-p90

codists

MySQL教学,是不是干货你说的算

java易二三

MySQL 数据库 程序员 计算机 电脑

山东布谷科技直播软件源码探索高效、稳定直播传输的技术介绍:流媒体传输技术

山东布谷科技

软件开发 直播 源码搭建 直播软件源码 流媒体技术

贡献超 10 万代码的新晋 committer,持续参与 Apache IoTDB 社区的“秘籍”是?

Apache IoTDB

“铁头乔”出品!CommunityOverCode Asia 专题介绍之物联网(IoT)/工业物联网(IIOT)

Apache IoTDB

加速解锁科学智能前沿,昇思MindSpore铸就了一把“全能”钥匙

脑极体

AI

万物皆可销售:数字世界中的商业文明之光

B Impact

网络虚拟世界不是法外之地,必须严打网络暴力

石头IT视角

Spring 简介

小万哥

Java spring 后端 spring-cloud spring-boot

面试官:说说Spring中@NotEmpty、@NotBlank、@NotNull 的区别和使用

java易二三

程序员 架构 计算机

向量检索在大模型应用场景的技术和实践

百度Geek说

人工智能 百度 企业号 8 月 PK 榜

产品管理经验分享:删掉 500 个产品待办事项后,我逃离了「假敏捷」

LigaAI

产品经理 敏捷开发 需求管理 产品管理 企业号 8 月 PK 榜

Rails: 用Resource_controller插件给Controllers减肥_Ruby_Rick DeNatale_InfoQ精选文章