1

我有一个像这样使用的 httparty “模型”

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

我将如何将其更改为类似于 activemodel 的工作,像这样?

RestModel.someGetRequest()
RestModel.somePostRequest()

这篇博客文章展示了如何包含单例模块,但它仍然像这样访问实例: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

请告诉我我做错了(给我看灯)

4

1 回答 1

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!"
于 2012-03-02T17:18:14.217 回答