【发布时间】:2011-10-11 11:11:35
【问题描述】:
我目前正在为新网站设计版本化 API。我了解如何命名路由,但我坚持在模型中实现版本化方法的最佳方式。
下面的代码示例使用的是rails框架,但事情的原理应该在大多数web框架之间是一致的。
目前的路线如下所示:
MyApp::Application.routes.draw do
namespace :api do
namespace :v1 do
resources :products, :only => [:index, :show]
end
end
end
还有控制器:
class Api::V1::ProductsController < V1Controller
respond_to :json, :xml
def index
respond_with @products = Product.scoped
end
def show
respond_with @product = Product.find(params[:id])
end
end
显然,我们只是在此处公开 Product 上可用的属性,如果您只需要一个 API 版本,此解决方案将非常有效。当您想要发布 V2 并且 V2 需要重新实现产品名称的显示方式(同时保持与 V1 的向后兼容性 - 至少在短期内)时会发生什么?
据我所知,您有几个选择...
- 立即放弃对 V1 的支持并处理后果(最坏的解决方案)
- 您开始覆盖 to_[format] 方法(我很确定您使用 as_[format] 执行此操作,但这不是重点)以包含一个新属性...
name_2- 这似乎同样愚蠢 - 实现某种代理类,只负责公开我们所追求的方法
- 让视图处理创建某种散列,版本化控制器并调用
to[format]on...
三个和四个是我真正认为有意义的唯一一个......三个看起来像:
# model
class Api::V1::Product < Struct.new(:product)
def to_json
attributes.to_json
end
def to_xml
attributes.to_xml
end
private
def attributes
{:name => product.name} # add all the attributes you want to expose
end
end
# Controller
class Api::V1::ProductsController < V1Controller
respond_to :json, :xml
def show
respond_with @product = Api::V1::Product.new(Product.find(params[:id]))
end
end
其他人过去做过什么?
【问题讨论】:
标签: ruby-on-rails ruby api architecture application-design