ActiveResource for no restful style
辛卯[兔]年 三月十九
上周群里有朋友在rails应用中需调用某api,不过接口非restful风格的,如要成功实现调用可以自行编写模块或引用第三方库,不过既然是在rails下,也可以拿AtciveResource来改动一下。
以下代码是个人做的一些小变更扩展来适应其api接口的调用--以下代码纯属实践娱乐,贴出来备忘。
# File config/initializers/active_resource_ext.rb
module ActiveResource
module Formats
module NoneFormat
extend self
def extension
""
end
def mime_type
""
end
def encode(hash, options = nil)
# 具体处理看实际需要
#ActiveSupport::JSON.encode(hash, options)
""
end
# to Base.instantiate_collection
def decode(json)
# 具体处理看实际需要
json
end
end
end
# ActiveResource::Base
class Base
class 〈〈 self
def element_path(id, prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
if format.extension == ""
"#{prefix(prefix_options)}#{collection_name}/#{URI.escape id.to_s}#{query_string(query_options)}"
else
"#{prefix(prefix_options)}#{collection_name}/#{URI.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
end
end
def new_element_path(prefix_options = {})
if format.extension == ""
"#{prefix(prefix_options)}#{collection_name}/new"
else
"#{prefix(prefix_options)}#{collection_name}/new.#{format.extension}"
end
end
def collection_path(prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
if format.extension == ""
"#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}"
else
"#{prefix(prefix_options)}#{collection_name}.#{format.extension}#{query_string(query_options)}"
end
end
def instantiate_collection(collection, prefix_options = {})
if collection.is_a? Array
collection.collect! { |record| instantiate_record(record, prefix_options) }
else
collection.to_s
end
end
end
end
# ActiveResource::Connection
class Connection
private
def build_request_headers(headers, http_method, uri)
if format.mime_type == ""
authorization_header(http_method, uri).update(default_header).update(headers)
else
authorization_header(http_method, uri).update(default_header).update(http_format_header(http_method)).update(headers)
end
end
end
end