Rails源码研究之ActionController:八,resources

本文深入探讨了 Rails 中 ActionController 的 Resources 模块如何实现 RESTful API,介绍了 resources 方法如何根据 HTTP 方法生成不同的资源操作,并展示了如何通过参数自定义路由。
深入了解一下ActionController的Resources--RESTful Rails

1,ActionController的resources用来实现REST api,一个单独的resource基于HTTP verb(method)有不同的行为(action),如:
[code]
map.resources :messages

class MessagesController < ActionController::Base
# GET messages_url
def index
# return all messages
end

# GET new_message_url
def new
# return an HTML form for describing a new message
end

# POST message_url
def create
# create a new message
end

# GET message_url(:id => 1)
def show
# find and return a specific message
end

# GET edit_message_url(:id => 1)
def edit
# return an HTML form for editing a specific message
end

# PUT message_url(:id => 1)
def update
# find and update a specific message
end

# DELETE message_url(:id => 1)
def destroy
# delete a specific message
end
end
[/code]

2,对于[b]map.resources :messages[/b]将生成如下named routes和helpers:
[code]
Named Routes Helpers

messages messages_url, hash_for_messages_url,
messages_path, hash_for_messages_path

message message_url(id), hash_for_message_url(id),
message_path(id), hash_for_message_path(id)

new_message new_message_url, hash_for_new_message_url,
new_message_path, hash_for_new_message_path

edit_message edit_message_url(id), hash_for_edit_message_url(id),
edit_message_path(id), hash_for_edit_message_path(id)
[/code]

3,由于浏览器不支持PUT和DELETE,我们需要添加:method参数,如:
[code]
<% form_for :message, @message, :url => message_path(@message), :html => {:method => :put} do |f| %>
[/code]

4,resources方法有一些参数:
[color=red]:controller[/color] -- specify the controller name for the routes.
[color=red]:singular[/color] -- specify the singular name used in the member routes.
[color=red]:path_prefix[/color] -- set a prefix to the routes with required route variables.
对于如下routes:
[code]
map.resources :articles
map.resources :comments, :path_prefix => '/articles/:article_id'
[/code]
我们可以使用嵌套写法:
[code]
map.resources :articles do |article|
article.resources :comments
end
[/code]
使用的时候多加一个:article_id参数即可:
[code]
comment_url(@article, @comment)
comment_url(:article_id => @article, :id => @comment)
[/code]
[color=red]:name_prefix[/color] -- define a prefix for all generated routes, usually ending in an underscore.
使用前缀来避免named routes名字冲突:
[code]
map.resources :tags, :path_prefix => '/books/:book_id', :name_prefix => 'book_'
map.resources :tags, :path_prefix => '/toys/:toy_id', :name_prefix => 'toy_'
[/code]
[color=red]:collection[/color] -- add named routes for other actions that operate on the collection.
比如对于如下route:
[code]
map.resources :messages, :collection => { :rss => :get }
[/code]
生成的named route为[b]rss_messages[/b],生成的helper方法为[b]rss_messages_path[/b],url则为[b]/messages;rss[/b]
该参数形式为#{action} => #{method}的hash,method为:get/:post/:put/:delete/:any,如果method无所谓则可以使用:any
[color=red]:member[/color] -- same as :collection, but for actions that operate on a specific member.
即:collection参数为对多个对象操作的方法,:member参数则为对单个对象操作的方法
[color=red]:new[/color] -- same as :collection, but for actions that operate on the new resource action.

5,map.resource的参数以及用法与map.resources差不多,只是map.resource为一个单独的resource生成named routes

源码全在resources.rb文件里,Rails经常这样弄的一个文件几百行甚至上千行代码,可读性很不好,不过倒也不错,不用到处找关联的文件
[code]
module ActionController
module Resources
class Resource
attr_reader :collection_methods, :member_methods, :new_methods
attr_reader :path_prefix, :name_prefix
attr_reader :plural, :singular
attr_reader :options

def initialize(entities, options)
@plural = entities
@singular = options[:singular] || plural.to_s.singularize
@options = options
arrange_actions
add_default_actions
set_prefixes
end

def controller
@controller ||= (options[:controller] || plural).to_s
end

def path
@path ||= "#{path_prefix}/#{plural}"
end

def new_path
@new_path ||= "#{path}/new"
end

def member_path
@member_path ||= "#{path}/:id"
end

def nesting_path_prefix
@nesting_path_prefix ||= "#{path}/:#{singular}_id"
end
end

class SingletonResource < Resource
alias_method :member_path, :path
alias_method :nesting_path_prefix, :path
end

def resources(*entities, &block)
options = entities.last.is_a?(Hash) ? entities.pop : { }
entities.each { |entity| map_resource entity, options.dup, &block }
end

def resource(*entities, &block)
options = entities.last.is_a?(Hash) ? entities.pop : { }
entities.each { |entity| map_singleton_resource entity, options.dup, &block }
end

private

def map_resource(entities, options = {}, &block)
resource = Resource.new(entities, options)
with_options :controller => resource.controller do |map|
map_collection_actions(map, resource)
map_default_collection_actions(map, resource)
map_new_actions(map, resource)
map_member_actions(map, resource)
if block_given?
with_options(:path_prefix => resource.nesting_path_prefix, &block)
end
end
end

def map_singleton_resource(entities, options = {}, &block)
resource = SingletonResource.new(entities, options)
with_options :controller => resource.controller do |map|
map_collection_actions(map, resource)
map_default_singleton_actions(map, resource)
map_new_actions(map, resource)
map_member_actions(map, resource)
if block_given?
with_options(:path_prefix => resource.nesting_path_prefix, &block)
end
end
end

def map_collection_actions(map, resource)
resource.collection_methods.each do |method, actions|
actions.each do |action|
action_options = action_options_for(action, resource, method)
map.named_route("#{resource.name_prefix}#{action}_#{resource.plural}", "#{resource.path};#{action}", action_options)
map.named_route("formatted_#{resource.name_prefix}#{action}_#{resource.plural}", "#{resource.path}.:format;#{action}", action_options)
end
end
end

def map_default_collection_actions(map, resource)
index_action_options = action_options_for("index", resource)
map.named_route("#{resource.name_prefix}#{resource.plural}", resource.path, index_action_options)
map.named_route("formatted_#{resource.name_prefix}#{resource.plural}", "#{resource.path}.:format", index_action_options)
create_action_options = action_options_for("create", resource)
map.connect(resource.path, create_action_options)
map.connect("#{resource.path}.:format", create_action_options)
end

def map_default_singleton_actions(map, resource)
create_action_options = action_options_for("create", resource)
map.connect(resource.path, create_action_options)
map.connect("#{resource.path}.:format", create_action_options)
end

def map_new_actions(map, resource)
resource.new_methods.each do |method, actions|
actions.each do |action|
action_options = action_options_for(action, resource, method)
if action == :new
map.named_route("#{resource.name_prefix}new_#{resource.singular}", resource.new_path, action_options)
map.named_route("formatted_#{resource.name_prefix}new_#{resource.singular}", "#{resource.new_path}.:format", action_options)
else
map.named_route("#{resource.name_prefix}#{action}_new_#{resource.singular}", "#{resource.new_path};#{action}", action_options)
map.named_route("formatted_#{resource.name_prefix}#{action}_new_#{resource.singular}", "#{resource.new_path}.:format;#{action}", action_options)
end
end
end
end

def map_member_actions(map, resource)
resource.member_methods.each do |method, actions|
actions.each do |action|
action_options = action_options_for(action, resource, method)
map.named_route("#{resource.name_prefix}#{action}_#{resource.singular}", "#{resource.member_path};#{action}", action_options)
map.named_route("formatted_#{resource.name_prefix}#{action}_#{resource.singular}", "#{resource.member_path}.:format;#{action}",action_options)
end
end
show_action_options = action_options_for("show", resource)
map.named_route("#{resource.name_prefix}#{resource.singular}", resource.member_path, show_action_options)
map.named_route("formatted_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}.:format", show_action_options)

update_action_options = action_options_for("update", resource)
map.connect(resource.member_path, update_action_options)
map.connect("#{resource.member_path}.:format", update_action_options)

destroy_action_options = action_options_for("destroy", resource)
map.connect(resource.member_path, destroy_action_options)
map.connect("#{resource.member_path}.:format", destroy_action_options)
end

def conditions_for(method)
{ :conditions => method == :any ? {} : { :method => method } }
end

def action_options_for(action, resource, method = nil)
default_options = { :action => action.to_s }
require_id = resource.kind_of?(SingletonResource) ? {} : { :requirements => { :id => Regexp.new("[^#{Routing::SEPARATORS.join}]+") } }
case default_options[:action]
when "index", "new" : default_options.merge(conditions_for(method || :get))
when "create" : default_options.merge(conditions_for(method || :post))
when "show", "edit" : default_options.merge(conditions_for(method || :get)).merge(require_id)
when "update" : default_options.merge(conditions_for(method || :put)).merge(require_id)
when "destroy" : default_options.merge(conditions_for(method || :delete)).merge(require_id)
else default_options.merge(conditions_for(method))
end
end

end
end

ActionController::Routing::RouteSet::Mapper.send :include, ActionController::Resources
[/code]

Resources模块定义了Resource类和SingletonResource类,前者表示多个资源,后者则表示单个资源
resources方法和resource方法分别调用map_resource方法和map_singleton_resource方法
map_resource和map_singleton_resource方法分别用Resource和SingletonResource类初始化对象
最后分别调用map.named_route和map.connect来生成各自的routes

注意resources和resource方法对生成的routes作了HTTP method上的限制,如果我们在request时提供的method参数有误则会抛出RoutingError异常

这样看来,resources只不过是为我们生成了一些named routes而已,简化了我们的工作,提高了效率

我们在看源码时带着问题去看,就会非常有收获
源码来自:https://pan.quark.cn/s/a4b39357ea24 《C++ Primer》作为C++编程领域中的一部权威著作,主要服务于初学者和经验丰富的开发者,致力于帮助他们深入掌握C++的核心知识。 第一章通常会详细讲解C++语言的基础概念和语法结构,包括变量的使用、数据类型的分类、常量的定义、运算符的应用以及基础的输入输出操作。 接下来,我们将对这一章中的核心知识点和可能的习题解答进行深入分析。 ### 1. 变量与数据类型在C++编程中,变量被视为存储数据的媒介。 每一个变量都必须预先声明其数据类型,常见的数据类型有整型(int)、浮点型(float)、双精度浮点型(double)以及字符型(char)。 例如:```cppint age = 25; // 声明一个整型变量age并赋予其初始值25float weight = 70.5f; // 声明一个浮点型变量weight并赋予其初始值70.5char grade = A; // 声明一个字符型变量grade并赋予其初始值A```### 2. 常量与字面量常量指的是不可更改的值,可以通过`const`关键字进行声明。 例如:```cppconst int MAX_SIZE = 100; // 声明一个整型常量MAX_SIZE,其值为100```字面量是指程序中直接书写的值,如`42`、`3.14`或`"Hello"`。 ### 3. 运算符C++提供了多种运算符,涵盖了算术运算符(+,-,*,/,%)、比较运算符(==,!=,<,>,<=,>=)、逻辑运算符(&&,||,!)以及赋值运算符(=,+=,-=,*=,/=,%=)等。 ### 4. 输入与输出在C++中,使用`std::cin`来实现输...
内容概要:本文详细介绍了一个基于C++的仓库存储管理系统的设计与实现,涵盖了项目背景、目标、挑战及解决方案,并系统阐述了整体架构设计、数据库建模、功能模块划分、权限安全、并发控制、数据一致性保障、异常处理与可扩展性等关键内容。通过面向对象编程思想,采用分层架构与模块化解耦设计,结合STL容器、多线程、锁机制等C++核心技术,实现了高效的库存管理功能,包括入库、出库、盘点、调拨、权限控制、日志追踪与智能报表分析。文中还提供了核心类如Inventory(库存)、User(用户权限)、LogEntry(操作日志)及WarehouseManager(主控制器)的代码示例,展示了数据结构设计与关键算法逻辑。; 适合人群:具备C++编程基础,熟悉面向对象设计与基本数据结构的软件开发人员,尤其适合从事企业级管理系统开发或希望深入理解系统架构设计的中级开发者(工作1-3年);也适用于计算机相关专业学生进行课程设计或毕业项目参考; 使用场景及目标:①学习如何使用C++构建复杂业务系统的整体架构与模块划分方法;②掌握高并发、数据一致性、权限控制、异常处理等企业级系统关键技术的实现思路;③理解仓储管理业务流程及其在软件系统中的建模与落地方式;④为开发类似ERP、MES等后台管理系统提供技术原型与设计参考; 阅读建议:此资源不仅提供理论架构与代码片段,更强调系统设计的完整性与工程实践性。建议读者结合代码示例动手实现核心模块,深入理解类之间的关系与交互逻辑,重点关注多线程安全、事务管理与权限校验等难点环节,并尝试扩展功能如对接GUI界面或数据库持久化模块,以全面提升系统开发能力。
农作物叶子健康与疾病实例分割数据集 一、基础信息 数据集名称:农作物叶子健康与疾病实例分割数据集 图片数量: - 训练集:7,446张图片 - 验证集:970张图片 - 测试集:182张图片 - 总计:8,598张图片 分类类别: - Apple Healthy(健康苹果叶) - Apple Rust Leaf(苹果锈病叶) - Apple Scab Leaf(苹果黑星病叶) - BellPepper Healthy(健康甜椒叶) - BellPepper Leaf Spot(甜椒叶斑病) - Corn Gray Leaf Spot(玉米灰斑病) - Corn Leaf Blight(玉米叶枯病) - Corn Rust Leaf(玉米锈病叶) - Grape Black Rot(葡萄黑腐病) - Grape Healthy(健康葡萄叶) - Squash Powdery Leaf(南瓜白粉病叶) - Tomato Bacterial Spot(番茄细菌性斑点病) - Tomato Healthy(健康番茄叶) - Tomato Septoria(番茄斑枯病) 标注格式:YOLO格式,包含实例分割的多边形标注,适用于实例分割任务。 数据格式:图片来源于农业图像数据库,细节清晰。 二、适用场景 农业植物疾病AI检测系统开发:数据集支持实例分割任务,帮助构建能够自动识别植物叶子疾病区域并分类的AI模型,辅助农民快速诊断和治理。 精准农业应用研发:集成至农业智能管理系统中,提供实时疾病识别功能,为农作物健康管理提供决策支持。 学术研究与创新:支持农业科学与人工智能交叉领域的研究,助力发表高水平农业AI论文。 农业教育与培训:数据集可用于农业院校或培训机构,作为学生学习植物疾病分类和诊断的重要资源。 三、数据集优势 精准标注与多样性:每张图片均经过准确标注,确保疾病区域分割精确。包
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值