Endless Parentheses

Ramblings on productivity and technical subjects.

profile for Malabarba on Stack Exchange

Turbo up your Ruby console in Emacs

Keeping a REPL (or a console) always by your side is never a bad habit, and if you use an IDE-package (like Robe for Ruby, or Cider for Clojure) it’s nigh unavoidable. Being an essential part of your environment, it would be ridiculous not to invest some time optimizing it.

One obvious optimization is to bind a key to your “start console” command, but that’s just the start. You pretty much never need two running consoles for the same project, so why not have the same key switch to it if it’s already running?

But we can go a bit farther with very little work. I have a file where I define a lot of small helper methods for my Ruby console, so let’s require it automatically whenever a new console is started.

(defcustom endless/ruby-extensions-file
  "../console_extensions.rb"
  "File loaded when a ruby console is started.
Name is relative to the project root.")

;; Skip ENV prompt that shows up in some cases.
(setq inf-ruby-console-environment "development")

(defun endless/run-ruby ()
  (interactive)
  (require 'inf-ruby)
  (let ((default-directory (projectile-project-root))
        (was-running (get-buffer-process inf-ruby-buffer)))
    ;; This function automatically decides between starting
    ;; a new console or visiting an existing one.
    (inf-ruby-console-auto)
    (when (and (not was-running)
               (get-buffer-process (current-buffer))
               (file-readable-p endless/ruby-extensions-file))
      ;; If this brand new buffer has lots of lines then
      ;; some exception probably happened.
      (send-string
       (get-buffer-process (current-buffer))
       (concat "require '" endless/ruby-extensions-file
               "'\n")))))

;; CIDER users might recognize this key.
(define-key ruby-mode-map (kbd "C-c M-j")
  #'endless/run-ruby)

If you use Projectile and want to go even faster, check out the j key on my post about Projectile.

comments powered by Disqus