2012-03-02 69 views
1

我有一個httparty「模型」,我用像這樣如何修改此類以使用單例模式,如activemodel?

myRest = RestModel.new 
myRest.someGetResquest() 
myRest.somePostRequest() 

我怎麼會去改變它的工作方式類似於一個activemodel的,像這樣?

RestModel.someGetRequest() 
RestModel.somePostRequest() 

blog post展示瞭如何在單模塊,但它仍然訪問這樣的實例:RestModel.instance.someGetRequest()

這裏是我的代碼:

class Managementdb 
    include HTTParty 

    base_uri "http://localhost:7001/management/" 

    def initialise(authToken) 
     self.authToken = authToken 
    end 

    def login() 
     response = self.class.get("/testLogin") 
     if response.success? 
      self.authToken = response["authToken"] 
     else 
      # this just raises the net/http response that was raised 
      raise response.response  
     end 
    end 

    attr_accessor :authToken 

    ... 
end 

請告訴我,我這樣做全部錯誤(向我展示燈光)

+0

使用Singleton模式使用'RestModel.instance.method()',get訪問例如支票將始終訪問它,如果一個已經創建並返回該實例或創建一個,如果它以前沒有使用過。在RestModel.method()中使用它將是靜態類的運行方式,而不是單身。 – jzworkman 2012-03-02 17:05:20

+0

好吧,如果我改變標題,你介意嗎? – 2012-03-02 17:07:44

+0

@jzworkman在Ruby中這不是真的。類的單例對象中存在Ruby中的「類」或「靜態」方法和屬性。 Ruby不是Java。 – 2012-03-02 17:14:07

回答

3

您想使用extend而不是include,它會將這些方法添加到類singleton中,而不是在實例上使它們可用。

class Managementdb 
    extend HTTParty 
end 

較長的例子說明這一點:

module Bar 
    def hello 
    "Bar!" 
    end 
end 
module Baz 
    def hello 
    "Baz!" 
    end 
end 
class Foo 
    include Bar 
    extend Baz 
end 

Foo.hello  # => "Baz!" 
Foo.new.hello # => "Bar!" 
+0

我是否仍然可以在'Foo'中使用'Baz'中的方法? – 2012-03-02 17:24:27

+0

@JosephLeBrech我不確定你的意思,你能澄清嗎? – 2012-03-02 17:25:18

+0

如果'Baz'有另外一個方法,我怎樣從'Foo'中的方法調用它? – 2012-03-02 17:26:52