2025上半年,最新 AI实践都在这!20+ 应用案例,任听一场议题就值回票价 了解详情
写点什么

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

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

关注

评论

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

java 虚拟机 GC :G1配置参数

风翱

GC 9月日更

分布式系统都要遵守的CAP

卢卡多多

CAP 9月日更

膜拜!不愧是阿里大牛总结的Java10W字面经,Github访问量已破百万

Java 程序员 架构 面试 计算机

基于虹软SDK,适配Camera1、Camera2、CameraX,实现人脸识别(Android)

小驰笔记

android 音视频 人脸识别 引航计划

阿里云天池赛题解析——深度学习篇重磅发布!

博文视点Broadview

如何利用国产图数据库打造金融行业方案?

星环科技

2021年最新整理, C++ 学习资料,含C++ 11 / 14 / 17 / 20 / 23 新特性、入门教程、推荐书籍、优质文章、学习笔记、教学视频等

奔着腾讯去

c++

「绝密档案」“爆料”完整秒杀架构的设计到技术关键点的“情报信息”

码界西柚

后端 秒杀系统 秒杀架构 秒杀架构设计 引航计划

linux之登录式shell和非登录式shell

入门小站

Linux

拒绝裸奔,为 Elasticsearch 设置账号密码(qbit)

qbit

https 安全 Kibana

乌镇回溯 | 构建网络空间命运共同体,旺链科技做了哪些?

旺链科技

数字经济 产业区块链 世界互联网大会

详解html5新增的标签与css3中伪类和伪元素

你好bk

html5 css3 大前端 基础技能

[外文资源]最好的 Golang 博客

baiyutang

golang 9月日更

13个VSCode使用技巧,开启高效的开发模式

华为云开发者联盟

vscode 日志 开发 插件 Git存储库

StartDT Hackathon | 泛元数据:让数据成为资产

奇点云

译文 | MySQL 8.0 密码管理策略(一)

RadonDB

MySQL 数据库

android逆向之root方式注入apk

轻口味

android 9月日更

多指标异常检测方法综述

云智慧AIOps社区

AIOPS 异常检测 技术学习 智能运维 指标

Python代码阅读(第30篇):找到列表中的奇偶异常项

Felix

Python 编程 Code Programing 阅读代码

被客户像小学生一样训话

boshi

创业

netty系列之:分离websocket处理器

程序那些事

Java 架构 Netty 程序那些事

月度发布 | 极狐GitLab14.3升级40+新功能!

极狐GitLab

带你了解数仓安全测试的TLS协议

华为云开发者联盟

安全 通信 密钥 SSL/TLS协议 加密通信

Go 语言实现 WebSocket 推送

全象云低代码

websocket 低代码开发 Go 语言

美女程序“媛”:从工程师到架构师,我的代码人生

融云 RongCloud

程序员 代码人生

在线黑客帝国文字效果生成工具

入门小站

工具

万亿养老市场如何抢占商机?云巢智慧康养物联网加速器,三招化解ISV痛点!

华为云开发者联盟

物联网 华为云 iotda 沃土云创计划 智慧康养

Talk to AI,揭秘背后的语音识别数据

澳鹏Appen

语音 nlp 语音识别 训练数据 语音识别模型

Prometheus 2.30.0 新特性

耳东@Erdong

release Prometheus 9月日更

扒一扒面向对象编程的另一面

华为云开发者联盟

编程 面向对象 对象 对象编程

第7章-《Linux一学就会》-Centos8 用户管理

学神来啦

Linux linux运维 linux学习 Linux教程

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