3

How to set user password dynamically for resource invocation. Person Resource could be invoked using John's password or Joe's password. How should I change this code, so that I can make this dynamic in nature.

class PersonResource < ActiveResource::Base
  self.site = "http://user:password@api.foo.com:3000/"
end
Rpj
  • 5,348
  • 16
  • 62
  • 122
  • How are you using `PersonResource.site` in your code, can you show a snippet, so that a better way can be figure out? – Kuldeep Feb 25 '15 at 07:50

1 Answers1

0

Just leave out the site class declaration:

class PersonResource < ActiveResource::Base
end

And then set site to the correct URL right before you use it:

PersonResource.site = "http://user:password@api.foo.com:3000/"
PersonResource.find(1)

Keep in mind that this is not thread safe. If you've enabled Rails threaded mode (via config.threadsafe!) then you could run into race conditions. If Rails is not in threaded mode then this approach is fine.

infused
  • 24,000
  • 13
  • 68
  • 78
  • No the above cannot be deployed in production, would need a more elegant solution. – Rpj Feb 19 '15 at 03:49
  • Here's a threadsafe solution https://stackoverflow.com/questions/8088126/is-it-thread-safe-to-set-active-resource-http-authentication-on-a-per-user-basis – infused Feb 19 '15 at 03:52