Mongoid and awesome_print, a simple patch!

Just a couple of days ago I had the need to print out some Ruby objects on my terminal in a nice and well formatted way.

The default p wasn’t enough for me and so, with just a couple of keystrokes, I end up on the github page of the well known awesome_print gem.

After adding the gem to my gem .gemspec (yep I need the pretty printing feature for my first gem :)) and requiring it inside the code I stumbled upon a little problem.

Here it is:

uninitialized constant Moped::BSON (NameError)

Moped, as written down here, is the supported MongoDB driver for the Ruby ODM library Mongoid (from version 3 and higher).

As a matter of fact I didn’t tell you that the objects I needed to print out weren’t just PORO (Plain Old Ruby Objects) but rather objects augmented with the Mongoid::Document module.

After a few minutes of tinkering with it I asked Google about the error and found that it was actually a known issue and the workaround was to simply define the missing constant.

But defining it with which value?

After a little bit more tinkering I found that (for the version of the libraries I was using i.e. mongoid 4.0.0moped 2.0.0 and awesome_print 1.2.0) the BSON constant is correctly defined in contrast with the previous one.

So the solution of my problem was simply:

Moped::BSON = BSON

I know, this is really nothing special.

Anyway there was something bothering me about this “nothing special patch assignment”. It was floating in my code freely with a little comment on it stating something like:

# this is to patch the error regarding blah blah blah...

Even to me it wasn’t feeling right.

So by thinking of a possible solution it came to my mind a nice resume I read some time ago about modules. Here it is.

Modules could be used to accomplish various different goals and maybe the most generic one is indeed to encapsulate “stuff”.

This perfectly fits my need and so I build up a little one in which I’m requiring the awesome_print gem and together with it I define the missing constant.

Here it is:

module PatchedAwesomePrint
  require 'awesome_print'
  ::Moped::BSON = ::BSON

Note that here I referred to both constants absolutely with the :: operator to properly address them.

In this way my patch is really encapsulated and all I needed to do to get rid of the error is to include the “patching” module i.e:

include PatchedAwesomePrint

As always I hope this can be helpful to everyone will face the problem I faced myself.


Leave a Reply

Please Login to comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.