There is no doubt that the rails console is amazingly helpful. At Ride we use it every day on our production application, so we wanted to add some custom helpers to make things easier for us.

But we use Pry and things got messy.

How does it normally work?

Normally adding a method is quite simple, Brandon Keepers has a great post about it. I added helpers that way at We Heart It where we used the default Rails console (IRB), but Ride uses Pry.

For the default setup, you just include a module in the Rails::ConsoleMethods module from a console block in your config/application.rb file.

This works because, rails extends IRB::ExtendCommandBundle with that module so everything in there is available by default.

This is how you get the controller method and other useful methods in your console.

But this doesn't work with Pry! Why? Because Pry only defines Pry::ExtendCommandBundle as an (empty) module to not break Rails but never uses it.

Making it work with Pry

After digging into the Rails and Pry's source code, I found a way to add our methods to the console by default. Instead of including our module in the rails module, we need to extend Pry's default bindings (TOPLEVEL_BINDING) like this:

# config/application.rb
console do
  require 'my_app/console'
  TOPLEVEL_BINDING.eval('self').extend MyApp::Console
end

This is exactly what happens in the pry-rails gem to add the Rails::ConsoleMethods methods, but since this also happens inside a console block we can't add our methods to the Rails module before it gets added to the binding, that's why we have to manually extend it.

I opened an issue in pry-rails since extending the TOPLEVEL_BINDING seems like a hack to me, but I could not find another way to do it. I had spent a lot of time trying to make it work and that worked, so ¯\(ツ)/¯.

I really hope this saves someone's time (and sanity), I got really frustrated for a while since there was no information about how to make this work (until now).