Question

I have a httparty "model" which I use like so

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

How would I go about changing it to work similarly to an activemodel, like so?

RestModel.someGetRequest()
RestModel.somePostRequest()

this blog post shows how to include the singleton module but its still accesses the instance like this: RestModel.instance.someGetRequest()

here is my code:

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

Please tell me that I am doing it all wrong (show me the light)

Was it helpful?

Solution

You want to use extend rather than include, which will add the methods onto the class singleton, rather than making them available on instances.

class Managementdb
  extend HTTParty
end

a longer example illustrating this:

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!"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top