Vladimir Penkin About GitHub LinkedIn

Pre and post hooks for external libraries with alias_method

Ever missing hooks in your favorite libraries? before_filter and after_fileter is not working outside rails? Thanks to ruby awesomness it’s never been an issue for programmers who know how to use alias or alias_method.

Problem

Here I am, sitting in front of laptop, writing yet another API wrapper. As I get tired of ruby native NET::HTTP requests and wanted to try something more explicit and gave a shot to HTTParty by John Nunemaker. Syntax is very simple and I came with following code:

But apparently interaction is not so easy as it seems. All authenticated calls must be signed. The process of signing include arguments that was passed to current method. So in every method that called, it needs sign data before sending:

Seems like unnecessary code duplication. Isn’t this kind of thing that pre-hook is made for? To solve this problem you diffinetly shouldn’t google for that.

After digging httparty source code I haven’t found some pre- or post- hooks. Seems like we need to do it ourselves.

Cooking hooks with alias_methiod

Thanks to greatness of ruby, I can open and modify native or external classes:

Ok now we have self-cooked before_get method that will be called before original HTTParty.get and will do the work:

Remember to put original_get arguments back with last line

Things to watch out

Be aware alias is keyword so there is no comma after name of new method. But alias_method is method version of alias.

Also do not crush others code. If I put Mugen.set_params in httparty_extensions.rb this can easily break other code that rely on HTTParty.

Comments

blog comments powered by Disqus
Fork me on GitHub