2012-09-26 43 views

回答

8
class User < ActiveResource::Base 
    self.element_name = "user" 
end 

接下來,你要問的是如何從看起來的ActiveResource被//foo.com/user.json代替//foo.com/user/.json

的URL得到一個元素
User.find(:one, :from => "https://foo.com/user.json?username=#{<USERNAME>}" 

編輯迴應評論

有沒有辦法做到這一點,而無需輸入請求的完整URL每一次我想用find()方法?

一種方法是在類中定義一個方法來爲您完成完整的URL。

class User < ActiveResource::Base 
    self.element_name = "user" 

    def self.find_by_username(username) 
    find(:one, :from => "https://foo.com/user.json?username=#{username}" 
    end 

    def find 
    self.class.find(:one, :from => "https://foo.com/user.json?username=#{username}" 
    end 
end 

另一種方法是重新定義element_path。

class User < ActiveResource::Base 
    self.element_name = "user" 

    def self.element_path(id, prefix_options = {}, options = {}) 
    "https://foo.com/user.json?username=#{prefix_options["user_id"]}" 
    end 
end 

有人會稱這個猴子補丁,其他人會稱之爲面向對象編程。我說這只是在進入代碼時使用猴子補丁,或者使用Ruby的動態特性來改變基本行爲,這是在面向對象編程中完成合法的方法。但是,Ruby社區不使用OOP多,幾乎忽略贊成要寬鬆得多(少很乖)的繼承混合插件,並且只用鴨打字的多態性。

具有惹的ActiveResource建,你不能重新定義Web服務接受的ActiveResource約定的URL的問題就是爲什麼很多使用HTTParty代替。 「如果你要建立的網址,還不如用HTTParty

+0

有什麼辦法要做到這一點,而不必輸入每一次我想使用find()的請求的完整URL? –

+0

你問了。回答編輯。 –

+1

你也可以使用'site'和'prefix'來組成URL的第一部分。 – funwhilelost

2

如果您只需要在URL擺脫資源名稱多元化的,覆蓋collection_name

class User < ActiveResource::Base 
    self.element_name = "user" 

    def self.collection_name 
    element_name 
    end 
end 
相關問題