Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch base_uri with httparty

Tags:

ruby

httparty

I am trying to pass a parameter to a login method and I want to switch the base uri based on that parameter.

Like so:

class Managementdb
  include HTTParty

  def self.login(game_name)
        case game_name
        when "game1"
            self.base_uri = "http://game1"
        when "game2"
            self.base_uri = "http://game2"
        when "game3"
            self.base_uri = "http://game3"
        end

    response = self.get("/login")

        if response.success?
      @authToken = response["authToken"]
    else
      # this just raises the net/http response that was raised
      raise response.response    
    end
  end

  ...

Base uri does not set when I call it from a method, how do I get that to work?

like image 591
Joseph Le Brech Avatar asked Mar 08 '12 11:03

Joseph Le Brech


People also ask

What is base_ uri?

In HTTParty, base_uri is a class method which sets an internal options hash. To dynamically change it from within your custom class method login you can just call it as a method (not assigning it as if it was a variable).


2 Answers

In HTTParty, base_uri is a class method which sets an internal options hash. To dynamically change it from within your custom class method login you can just call it as a method (not assigning it as if it was a variable).

For example, changing your code above, this should set base_uri as you expect:

...
case game_name
  when "game1"
    # call it as a method
    self.base_uri "http://game1"
...

Hope it helps.

like image 59
Estanislau Trepat Avatar answered Sep 21 '22 16:09

Estanislau Trepat


I can’t comment yet, so here’s an extension to Estanislau Trepat’s answer.

To set the base_uri for all your calls, call the according class method:

self.base_uri "http://api.yourdomain.com"

If you want to have a way of sending only a few calls to a different URI and avoid state errors (forgetting to switch back to the original URI) you could use the following helper:

def self.for_uri(uri)
  current_uri = self.base_uri
  self.base_uri uri
  yield
  self.base_uri current_uri
end

With the above helper, you can make specific calls to other URIs like the following:

for_uri('https://api.anotheruri.com') do
  # your httparty calls to another URI
end
like image 36
j4zz Avatar answered Sep 22 '22 16:09

j4zz