Ruby on Rails中的ActiveResource使用详解

当 HTTP 响应是一个与存在的格式不同的格式时(XML 和 JSON),需要某些额外的格式解析,创一个你惯用的格式,并在类别中使用它。惯用的格式应当实作下列方法: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)
       # 数据以新格式编码并返回
      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 方法,并移除扩展的部分。

  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

    如有任何改动网址的需求时,这些方法也可以被覆写。