分享 初学者连载系列之十:具备表象状态迁移 (REST)

kevinhua · April 06, 2012 · 3782 hits

系列文章原载于自己的博客,TOPI.CO (http://topi.co) ,某天不小心就 push 错啦,懒得从头再来,上传到 Ruby-China 来,一是方便自己回顾,另外也方便跟我一样的初学者

具备表象状态迁移 (Representational State Transfer, REST) 或称为表象化状态迁移。它代表了分布式超媒体系统的体系结构风格,该风格中是 Roy Fielding 在论文中定义。REST 在系统中加入一系列的限制,为确保极大的可扩展性。虽然 REST 定义了大量的重要体系结构限制 (例如将用户接口和服务器实现的清晰分离、无状态、以及缓存能力)。REST 关键的特有能力是统一接口的要求。REST 接口是由 HTTP 接口定义的,支持 GET/POST/PUT/DELETE。这种统一接口限制,跟面向服务的体系结构 (Service-Oriented Architecture, SOA) 相反,后者为每种类型的服务定义了不同的接口。

REST 构架风格具有以下设计准则:

  • 网络上的所有事物都抽象为资源 (resources = data + representation)
  • 每个资源都对应一个唯一的资源标识 (resources identifier = url)
  • 通过连接器 (generic connector interface) 对资源进行操作 (generic connector = HTTP Protocol 即 GET/POST/PUT/DELETE) * 对资源的各种操作不会改变资源标识 (对资源的 GET 操作不改变资源的状态)
  • 所有操作都是无状态的 (stateless)

从 Rails 1.2 开始,Rails 引入了完全 REST 化的 API 支持。路由 (routes) 实现了资源 (resources) 的概念,而 representation(表象) 则由 respond_to 方法实现。RESTful 带给 Rails 最大的好处是:它帮助我们用一种比较标准化的方式来命名和组织 Controllers 和 Actions。在没有 RESTful 之前,典型路由的设计是逐一指定 Controller 和 Action。

将 RESTful 带入 Rails 路由系统的构思,出自它对应了 HTTP 动词# POST/GET/PUT/DELETE到数据的新增、读取、更新、删除等四项操作。原来的路由:

HTTP method:在HTTP1.1通信协义中定义了九种单词,分别是:HEAD/GET/POST/PUT/DELETE/TRACE/OPTIONS/CONNECT/PATCH

  • /topics/create
  • /topics/show/id
  • /topics/update/id
  • /topics/destroy/id

将会变成:

  • POST /topics 对应到 Controller 中的 creat action
  • GET /topics/id 对应到 Controller 中的 show action
  • PUT /topics/id 对应到 Controller 中的 update action
  • DELETE /topics/id 对应到 Controller 中的 destroy action

因此,Rails 的路由设定很大程度上简化,只须在 config/routes.rb 中加入下行:

resources :topics

如此,会自动创建 4 个命名路由 (named routes),搭配四个 HTTP 动词,对应在到七个 Actions,它的实际作用,就如同以下的设定:

get '/topics'       => "topics#index",  :as => "topics"
post    '/topics'       => "topics#create", :as => "topics"
get '/topics/:id'   => "topics#show",   :as => "topic"
put '/topics/:id'   => "topics#update", :as => "topic"
delete  '/topics/:id'   => "topics#destroy",:as => "topic"
get '/topics/:id'   => "topics#new",    :as => "new_topic"
get '/topics/:id/edit'  => "topics#edit",   :as => "edit_topic"

可以参考下表:

Helper GET POST PUT DELETE
topic_path(@topic) /topics/id
topics#show
/topics/id
topics#update
/topics/id
topics#destroy
topics_path /topics
topics#index
/topics
topics#create
edit_topic_path(@topic) /topics/id/edit
topics#edit
new_topic_path /topics/new
topics#new

注意,这七个 Action 方法的名字是 Rails 约定好的,无法修改。因此,链接可以写成:

link_to topic.name, topic_path(@topic)

而不是写成:

link_to topic.name, :controller => 'topics', :action => :show, :id => topic.id

因此,只需记得资源 (resources),就可以写成 URL Helper:

[custom route_]topic[s]_path(@topic), :method => GET | POST | PUT | DELETE

注意,_path 结尾对应相对网址,而_url 结尾对应完整的网址 (包含域名)。

本文参考:RESTful 应用程式,Ruby on Rails 实战圣经,iHower

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.