Tips and Tricks: Gem pristine

A while ago, some friends and I were doing some code exploration inside gems, trying to figure out how they worked. All was well and good until we had changed everything and broke the gem. Here are a few great commands for playing around with this stuff, and then resetting it when you are done so everything on your system still works the way it is supposed to.

To open a gem in your default text editor and poke around it’s squishy inner bits:

bundle open GEMNAME

EX:

bundle open rake

Once you are done playing around and just want things to go back to the way they were, there are two good commands to know.

For when you have bundler set up to install gems to a local vendor directory, and that is the gem you were playing with:

bundle exec gem pristine GEMNAME

Or if you want to restore all the possible versions of a gem:

gem pristine GEMNAME

Happy hacking!

Tips and Tricks: JSON in IRB or Pry

Trick one: Parse your raw JSON objects when you pull them in.

For our Ruby Gem project, we were pulling down JSON-formatted data from the Wikipedia  API. To successfully work with JSON in IRB, I imported the object with an HTTP gem and then parsed the JSON data with the JSON gem. EX:

require 'json' 
require 'rest_client' 
JSON.parse(RestClient.get <URL>)

Which gives us a nice Hash output that looks like this:

{"query-continue"=&gt;
    {"images"=&gt;
        {"gimcontinue"=&gt;"736|Citizen-Einstein.jpg"}},
    "query"=&gt;
        {"pages"=&gt;
            {"-1"=&gt;{"ns"=&gt;6, "title"=&gt;"File:1919 eclipse positive.jpg", "missing"=&gt;""},
             "-2"=&gt;{"ns"=&gt;6, "title"=&gt;"File:Albert Einstein's exam of maturity grades (color2).jpg", "missing"=&gt;""}}}}

Without parsing, the information was still in JSON format, a thing that looked like:

"{\"query-continue\":{\"images\":{\"gimcontinue\":\"736|Citizen-Einstein.jpg\"}},\"query\":  ...

with extra quotation marks and all the backslashes, and Ruby got pretty cranky about trying to work with that string.

Trick Two: ‘puts’ your JSON

For another project, I was converting hashes into JSON, and I was getting a bit frustrated. I was quite certain that I was converting the hash into JSON correctly, but I kept getting extraneous backslash-escaped quotation marks in my JSON returns like before.

"{\"query-continue\":{\"images\":{\"gimcontinue\":\"736|Citizen-Einstein.jpg\"}}, ...

Thanks to some StackOverflow googling, I realized/remembered that this was because I was directly calling the JSON in the console, instead of puts-ing it from within the script I was running. When I used a puts statement inside the script, I could see that my output was actually formatted correctly, as I expected. Using puts in the console also worked to show me the JSON with it’s correct formatting.

puts <JSON>

instead of

<JSON>