Ruby on Rails中的ActiveResource使用详解

(编辑:jimmy 日期: 2024/9/22 浏览:2)

当 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

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

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。