Tuesday, August 21, 2007

ActiveResource Monkey-Patch: Create ARes Models From Vanilla Gets

I don't buy the REST dogma. I don't know why not, it just doesn't fly with me. However, many times when I've decided DHH was wrong, he's turned out to be right. So it's entirely possible he could turn out to be right here as well.

However, in the meantime, between now and the moment when I see the light, I've got a lot to do, and sometimes the steps you have to take to make your Rails apps conform to "pure" REST feel like a serious waste of time to me. There are some times when you just want to be able to call a get() on an ARes model as if it was a find(). Assuming you're hitting an API which sends ActiveRecord models back using to_xml, all you have to do to enable that is break the privacy on instantiate_collection.

You then call it like this:

Model.build_from_hash(Model.get(:method_name))

Caveats! I've just started hacking with ActiveResource, and I haven't started drinking the REST Kool-Aid. I'm probably doing it wrong. But it gets the job done.



Also, you can still run into trouble on included objects from association classes.

Update: I'm totally doing it wrong. My build_from_hash method takes an array. Please consider this post nothing more than notes on a work in progress.

Update 2: here's a substantially less dumb version. Needs refactoring though - the code is pretty heinous. It's mostly based on working around Rails' assumptions, when it should be working with them. However, the cool thing is that this version is almost entirely portable for plural association classes. That being said, it's currently only useful for plural classes. The exception to "entirely portable" is the ActiveResource get, which needs to be a find(:include) (which is coming).

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.