現在、新しい Web サイト用にバージョン管理された 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 のバージョンが 1 つしかない場合にうまく機能します。V2 をリリースしたいのですが、V2 で製品名の表示方法を再実装する必要がある場合はどうなりますか (V1 との下位互換性を維持しながら - 少なくとも短期的には)。
私が見る限り、いくつかのオプションがあります...
- V1 のサポートをすぐに中止し、フォールアウトに対処する (考えられる最悪の解決策)
- 新しい属性を含めるために to_[format] メソッドをオーバーライドし始めます (as_[format] でこれを行うと確信していますが、それは重要ではありません)...
name_2
- これは同様にばかげているようです - 必要なメソッドのみを公開する役割を担うある種のプロキシ クラスを実装します。
- ビューに、バージョン管理されたコントローラーが呼び出すある種のハッシュの作成を処理
to[format]
させます...
Three と Four は、私が実際に何らかの意味があると考えることができる唯一のものです... Three は次のようになります。
# 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
他の人は過去に何をしましたか?