Sunday, February 10, 2008

ActiveResource Instance Authentication Plugin: Dapper Resource

Presenting Dapper Resource, an ActiveResource instance authentication plugin.

script/plugin install

You know how you define ActiveResource models like this?

That call hits a site class method which then generates an ActiveResource::Connection object and makes it a class-level attribute.

But there's a problem. A user later needed HTTP authentication on their ARes models, so it was added in the same place: = "http://user:pass@localhost:12345/"

But if you store the username and password at the class level, you can't map your Rails app's users directly to your Web service's users - because each instance of the class will have different credentials. (I've posted about this before - here and here.)

Dapper Resource moves the connection object down to the instance level. For find calls, I wish I could say I wrapped the generation of a new connection object with appropriate credentials up into the ARes initialize, but I didn't. I was in a hurry, and I always go by YAGNI unless given a really good reason not to. So for find, you can just pass in an arbitrary connection object to find itself. (Also, if you don't provide specific connections, your ARes models will default to the class-level connection.)

Here it is:

script/plugin install

Hope you dig it.