Today we’ll take a quick look at one of my favorite gems: interactive_editor. Have you ever been in a REPL session (rails console, irb, pry, etc.) and wished that you could pop open a full editor to write out some code? (Ok, maybe not you pry users.) Well interactive_editor is a gem that gives you just that, as well as some really nice object inspection and manipulation.
The dark times
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
So that’s a pain. The usual alternative is to pop over to an editor and prototype out the code there, but that’s getting less fun. Sure you can execute ruby code from just about any editor and see the results, but you’re limited to what you explicitly print out. You lose the ability to play with your objects directly.
Wouldn’t it be nice if you could just integrate your editor of choice into your REPL of choice?
You can. It’s what interactive_editor does.
What you’d see next is my full vim open up a temporary file. It’s not a pseudo vim, not a generic vim, it’s my vim with my theme, plugins, and configuration.
You aren’t limited to vim either! Out of the box it supports a bunch of editors like TextMate and emacs. You can also configure any editor that you can launch from the command line, you just have it set it up.
Any code you enter into the editor session is executed in the irb session when you save and quit.
If you type ‘vim’ again, it reopens that same temporary file. Perfect for editing a class over and over again until things work as you want them to.
Because ruby is ruby, if you edit a class in the vim session even objects you’ve instantiated will get the updated code.
But we’re not limited to writing new code. interactive_editor also adds methods to Object that will launch any of its configured editors. Calling that method will open any object in YAML representation. You can even edit the YAML and when you save/quit your editor it will be written back out just as if you had manually typed in all the YAML in the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Change that to:
Save and quit.
Amazing! This is particularly handy for inspecting complicated Rails models. Unfortunately for that it only works well if you aren’t using sqlite because the YAML representation of a sqlite model doesn’t show column names.
If you use this YAML editing trick to change a Rails model, you need to know a trick. Because you’ve edited the model data directly and bypassed the Rails updating methods, Rails doesn’t consider anything in the model to be changed. You need to flag specific fields to update with the “will_change!” method.
1 2 3 4 5 6 7 8 9
1 2 3
Intrigued? Interested? I hope so. interactive_editor is one of my favorite tips. I have my .irbrc configured to automatically load it so I can just get going easily on any code prototyping or introspection that I care to tackle.
Check it out on github: https://github.com/jberkel/interactive_editor