當(dāng) HTTP 響應(yīng)是一個與存在的格式不同的格式時(XML 和 JSON),需要某些額外的格式解析,創(chuàng)一個你慣用的格式,并在類別中使用它。慣用的格式應(yīng)當(dāng)實作下列方法:extension, mime_type,
encode 以及 decode。
module ActiveResource
module Formats
module Extend
module CSVFormat
extend self
def extension
'csv'
end
def mime_type
'text/csv'
end
def encode(hash, options = nil)
# 數(shù)據(jù)以新格式編碼并返回
end
def decode(csv)
# 數(shù)據(jù)以新格式解碼并返回
end
end
end
end
end
class User ActiveResource::Base
self.format = ActiveResource::Formats::Extend::CSVFormat
...
end
若 HTTP 請求應(yīng)當(dāng)不擴展發(fā)送時,覆寫 ActiveResource::Base 的 element_path 及 collection_path 方法,并移除擴展的部分。
class User ActiveResource::Base
...
def self.collection_path(prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}"
end
def self.element_path(id, prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}/#{URI.parser.escape id.to_s}#{query_string(query_options)}"
end
end
如有任何改動網(wǎng)址的需求時,這些方法也可以被覆寫。
您可能感興趣的文章:- 關(guān)于Ruby on Rails視圖編寫的一些建議
- 關(guān)于Ruby on Rails路由配置的一些建議
- 詳解Ruby on Rails中的Cucumber使用