如何修改此类以使用单一模式,如activemodel?

时间:2012-03-02 17:01:28

标签: ruby singleton httparty

我有一个我喜欢的httparty“模型”

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

请告诉我,我做错了(告诉我光明)

1 个答案:

答案 0 :(得分:3)

您希望使用extend而不是include,这会将方法添加到类单例中,而不是在实例上使用它们。

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!"