Ruby on Rails中的ActiveResource使用詳解
當(dāng) HTTP 響應(yīng)是一個(gè)與存在的格式不同的格式時(shí)(XML 和 JSON),需要某些額外的格式解析,創(chuàng)一個(gè)你慣用的格式,并在類別中使用它。慣用的格式應(yīng)當(dāng)實(shí)作下列方法: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) # 數(shù)據(jù)以新格式編碼并返回 end def decode(csv) # 數(shù)據(jù)以新格式解碼并返回 end end end end end class User < ActiveResource::Base self.format = ActiveResource::Formats::Extend::CSVFormat ... end
若 HTTP 請(qǐng)求應(yīng)當(dāng)不擴(kuò)展發(fā)送時(shí),覆寫 ActiveResource::Base 的 element_path 及 collection_path 方法,并移除擴(kuò)展的部分。
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
如有任何改動(dòng)網(wǎng)址的需求時(shí),這些方法也可以被覆寫。
相關(guān)文章
Ruby日期時(shí)間的比較,日期轉(zhuǎn)換等時(shí)間日期處理方法大全
這篇文章主要介紹了Ruby的日期時(shí)間處理方法與函數(shù),日期時(shí)間和字符串、數(shù)值之間的轉(zhuǎn)換,日期時(shí)間的比較需要的朋友可以參考下2022-04-04Ruby實(shí)現(xiàn)插入排序算法及進(jìn)階的二路插入排序代碼示例
插入排序即是把已有的有序序列從后向前掃描插入元素,數(shù)值大的向后移動(dòng),這里我們就來看一下使用Ruby實(shí)現(xiàn)插入排序算法及進(jìn)階的二路插入排序代碼示例2016-06-06