I’m writing a Ruby interface to Fluidinfo, using the rest-client gem as a basis. I really like how calls to RestClient automatically return the body unless you call the code/headers/etc. method, and I’d like to preserve that functionality. The problem is that I want to have the JSON that Fluidinfo returns pre-parsed, so users don’t have to worry about it. I wouldn’t really care so much about that, except that in some cases Fluidinfo will return a value like "foo", which isn’t technically JSON, so the basic JSON gem won’t parse it. I’m using YAJL instead, which accepts these primitive values.
I’m very new to Ruby (mainly familiar with Python and Perl), so I’m not really sure how to do this. Can I just subclass RestClient::Response and override the create method? I know in Ruby you can open classes and redefine methods, but I’m not sure that’s a good idea in this case.
Any advice would be appreciated.
Redefining the
createmethod ofRestClient::Responsewould break its original functionality for rest-client used side-by-side with your interface. As the rest-client gem is a frequently used gem, this could not be what you wanted.In such a situation I write a wrapper class having an instance of the original one, write alias methods to call on the original instance and redefine the necessary methods.
The aliases can be a little short-handed using common
requestmethod which doessendto the original instance; aliases only callrequest :method_name, *argsthen.This way I wrapped rest-client to work as a simple user agent storing cookies and to redefine the class-global
RestClient.proxyvariable before each request. I needed both rest-client and couchrest (couchrest using rest-client itself) where I did want to make rest-client requests via proxy myself and do a straight requests from couchrest which I had to wrap as well.I know it is not an elegant solution but in my less-than-a-year ruby experience I know not of a better one. Perhaps somebody shows us a better one, I would like to read it as well.