23. MonkeyPatch一例(その1) module ActiveResource class Base class << self def find(*args) find_with_response(*args)[0] enddef find_with_response(*args) scope = args.slice!(0) options = args.slice!(0) || {} case scope when :all then list, body = find_every(options) return list, body when :first then list, body = find_every(options) return list.shift, body when :last then list, body = find_every(options) return list.pop, body when :one then record, body = find_one(options) return record, body else record, body = find_single(scope, options) return record, body end end end endActiveResource::Base.find_with_response を追加 ※レスポンスを生Hashでも返し、 Pagerの実装に用いる。ActiveResource::Base.find は find_with_responseを利用するよう書き換え。 list, raw_data = Journal.find_with_response(:all)raw_data[:totalnum]#=> 20
24. MonkeyPatch一例(その2)require 'json/ext'module ActiveResource class Connection def get(path, headers = {})JSON.parse(request(:get, path, build_request_headers(headers, :get)).body) end endendActiveSupportではなく、json/extを利用してJSONのパースを行うMonkeyPatch一例(その3)class Journal < ActiveResource::Base self.site = "http://foo.com" self.format = :json class << self def element_path(id, prefix_options = {}, query_options = nil) prefix_options, query_options = split_options(prefix_options) if query_options.nil?"/journals/#{id}#{query_string(query_options)}" end def collection_path(prefix_options = {}, query_options = nil) prefix_options, query_options = split_options(prefix_options) if query_options.nil?"/journals#{query_string(query_options)}" end def instantiate_collection(body, prefix_options = {}) return body['container']['list'].collect! { |record| instantiate_record({'container' => record}, prefix_options)[0] }, body end def instantiate_record(body, prefix_options = {}) record = new(body['container']).tap do |resource| resource.prefix_options = prefix_options end return record, body end endend(※赤字部分がAPI依存箇所)