當 HTTP 響應是一個與存在的格式不同的格式時(XML 和 JSON),需要某些額外的格式解析,創一個你慣用的格式,并在類別中使用它。慣用的格式應當實作下列方法:extension, mime_type,
encode 以及 decode。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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 ) # 數據以新格式編碼并返回 end def decode(csv) # 數據以新格式解碼并返回 end end end end end class User < ActiveResource::Base self .format = ActiveResource::Formats::Extend::CSVFormat ... end |
若 HTTP 請求應當不擴展發送時,覆寫 ActiveResource::Base 的 element_path 及 collection_path 方法,并移除擴展的部分。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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 |
如有任何改動網址的需求時,這些方法也可以被覆寫。