Samstag, 26. Oktober 2013

Custom Viewer

With release 0.9.17 watobo introduced a new viewer pane. This custom viewer gives you full control of how the output should look like. It enables you to parse the response (extract, format, decode, …) and display only the relevant parts by using the power of ruby – an example will follow shortly.
The custom viewer is available in the main window’s response viewer as well as in the manual request editor response - the latter we use for this tutorial.
Here’s the place we’re talking about:


Example

Our example function takes two parameters ‘char’ and ‘count’. The JSON response contains the parameter ‘answer’, which looks based64 encoded:


For decoding, select the base64 string, right-click and send it to watobo’s transcoder …

and finally decode it. But it still doesn't look human readable:




There's no well known magic-byte, but because of the two parameters ‘char’ and ‘count’ … bla … bla … bla … I know that the response is deflated with zlib ;)
Let’s proof it in irb:
>> require 'zlib'
>> require 'base64'
>> Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate Base64.decode64("Cw+HAQA=")
WWWWWWWWWW


This looks much better!

Cool, but it is not very comfortable if you have to copy-paste this string for each single response. So this is the time for the custom viewer.To automate this process (extract, decode and finally inflate) we only have to write a small handler. This handler consists of a ruby-lambda which receives the response object as an argument.

The very handler skeleton looks like this:
lambda{|response|
}


Because the return value of the handler function will be displayed,  it is a good choice to return a string.


The final code should look like this:

lambda{|response|
  h = JSON.parse(response.body.to_s)
  bin = Base64.decode64(h[‚answer‘])
  Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate bin
}


Now, save it and go on with the custom viewer:


You should see the red sign "No handler!". Press ‘add’ and select our freshly created handler file.
The sign should have been turned green, saying "Handler ready!"

*DRUMS_PLEASE* … press “SEND” … et voilà!



The viewer shows only the extracted, decoded and finally inflated value.

If you like it, please spread the word!

[as]