在 2025 收官前,看清 Data + AI 的真实走向,点击查看 BUILD 大会精华版 了解详情
写点什么

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:591719
用户头像

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

关注

评论

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

2023年最具威胁的25种安全漏洞(CWE TOP 25)

华为云开发者联盟

安全 华为云 安全漏洞 华为云开发者联盟 企业号 7 月 PK 榜

软件定义汽车场景中的数据流处理

EMQ映云科技

车联网 mqtt 数据流

人工智能的底层逻辑

博文视点Broadview

重塑未来的1课:组装式交付新引擎——华为云智能化低代码平台

云计算 低代码 华为云 华为开发者大会

大学生活动社交小程序开发笔记(1)

CC同学

直播预告 | 博睿学院:海量数据实时可信认证

博睿数据

智能运维 博睿数据 数据要素 博睿学院

MatrixOne悲观事务实现

MatrixOrigin

数据库 分布式 云原生 矩阵起源

如果AI能帮我 | 社区征文

六月的雨在InfoQ

AIGC ChatGPT 年中技术盘点 通义听悟

低代码技术分享官丨inBuilder使用有向无环图助力元数据工程依赖管理

inBuilder低代码平台

分布式系统常见问题

互联网工科生

分布式

创新引领!矩阵起源荣获中国信通院双重认可!

MatrixOrigin

数据库 分布式 云原生 超融合 矩阵起源

方言语音识别数据驱动人工智能的多元文化发展

数据堂

方言语音

沉潜蓄势,厚积薄发:StoneDB-5.7-V1.0.4版本正式发布!特性增强,稳定性大幅提升

StoneDB

数据库 版本发布 StoneDB

用友BIP全球司库“五大管家”,助力大型企业一流司库建设

用友BIP

全球司库

软件测试/测试开发丨Selenium环境安装配置

测试人

Python 程序员 软件测试 selenium chromedriver

三问三答:细数GaussDB迁移的核心技术

华为云开发者联盟

数据库 后端 华为云 华为云开发者联盟 企业号 7 月 PK 榜

为什么选择美国虚拟主机是你的明智之选?

一只扑棱蛾子

美国虚拟主机

从零开始构建一个电影知识图谱,实现KBQA智能问答[下篇]:Apache jena SPARQL endpoint及推理、KBQA问答Demo超详细教学

汀丶人工智能

人工智能 自然语言处理 知识图谱 智能问答 KBQA

接口文档阅读方法:程序员必备的技术指南

Liam

程序员 接口文档 API

【HDC.Cloud 2023】华为云区块链分论坛内容值得再读!

华为云开发者联盟

区块链 后端 华为云 华为云开发者联盟 企业号 7 月 PK 榜

从零开始构建一个电影知识图谱,实现KBQA智能问答[上篇]:本体建模、RDF、D2RQ、SPARQL endpoint与两种交互方式详细教学

汀丶人工智能

人工智能 自然语言处理 nlp 知识图谱 本体建模

实例分享| anyRTC 部署安徽某市应急实战指挥平台

anyRTC开发者

音视频 快对讲 融合会议 视频监控 综合调度

GPT-4被破解!数智时代大突破!低代码开发平台揭秘:AI模型架构演进的利器

不在线第一只蜗牛

人工智能 低代码 模型调参 ChatGPT GPT-4

科兴未来|“追光逐电 才聚紫琅”光电产业创新创业大赛

科兴未来News

超级应用App的概念及构建思路

Onegun

小程序 小程序容器 超级应用

火热的低代码和无代码赛道

互联网工科生

软件开发 低代码 无代码 应用开发

Cloud Kernel SIG月度动态:ANCK 5.10-016将落地kABI机制,5.10-015版本规划发布

OpenAnolis小助手

操作系统 内核 anck 龙蜥sig 版本规划

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