Search code examples
rubyrestoauthrest-client

How can I instantiate Ruby's RestClient?


I need to get 2 different 'clients' for testing purposes(user/agent e-wallet mobile apps):

  • 1 for user client
  • 1 for agent client

Both of these clients should be signed with ouath headers. RestClient provide #before_execution_proc for such purposes, but this won't work for 2 different sessions at once. I've tried solve it with this pull request, but this is ugly way for multi resource(as I should run this code with every new resource requested):

def resource(url)
  rest = RestClient::Resource.new(@base_url+ url)
  rest.add_before_execution_proc do |req, params|
    @access_token.sign! req, {"Cookie" => @cookies}
  end
  rest
end

Solution

  • I would go with preparing a hash url_regexp ⇒ access_token and generic add_before_execution_proc:

     @access_tokens = { /google/ => ..., /msoft/ => ... }
     RestClient.add_before_execution_proc do |req, params|
       token = @access_tokens.detect { |req_rex, token| req_rex =~ req }.last
       token.sign!(req) unless token.nil?
     end
    

    Of course the check should be done carefully, probably depending on both request and params.