rubyhttparty

How to switch base_uri with 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?


Solution

  • 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.