Übergeek UnLtd

notes from dr. Awkward's holistic geekery

Sublime Text Tutorial for Use With Rails and Rspec on Mac

| Comments

While the world did not end yesterday, my subscription to Rubymine and Textmate both expired. And they will probably not be renewed since I made a new friend: Sublime Text. For the past few days I have been busy switching. This post is all my wisdom on setting up Sublime Text code editor (well, IDE?) on mac osx with special attention to use it with ruby and rails.

Packages

Install package control

After installing Sublime, first thing is to install package control, which allows you to manage Sublime extensions as well as takes care of automatic updates of add-ons. Not sure why this is not part of the editor base, but it is defo a must. Its installation is somewhat funny but well documented and quick:

Now you manage packages via the command palette (cmd+shift+P) > package control or via Sublime > Preferences > package control. It is a tad annoying that after choosing a package, all dialogs disappear, so to install several packages, you need to go through 4 clicks again. (I'm yet to find out how to script package installation…)

Some of the must-have packages:

  • Soda theme. this is the hypest theme clearly, most webcasters use it. I'm told it improves code readability, so I just installed it.
  • I am yet to find a proper non-dark color scheme though. Candidate bright ones are iPlastic, IDLE, Lazy, Mac Classic, Dawn, Eiffel but none rich enough. This fantastic gallery shows the default color schemes to give you an idea.
  • beautifyRuby, RSpec, RubyTest, DetectSyntax and Git for ruby devel, etc. see full list and details below
  • CTags (needs brew install ctags)
  • fetch: http://net.tutsplus.com/articles/news/introducing-nettuts-fetch/ starting new projects super easy.
  • list of all: http://wbond.net/sublime_packages/community

Sublime Text 2 stores all under ~/Library/Application Support/Sublime Text 2. The Packages subdir contains the default packages that ship with the editor, including all basic bundles. It is also by default the install target of package control custom extensions.

Here is the full list of my custom packages so far:

  • Alignment
  • Alternative Autocompletion
  • BeautifyRuby
  • CTags
  • DetectSyntax
  • ERB Insert and Toggle Commands
  • Git
  • Haml
  • Nettuts+ Fetch
  • RSpec
  • RSpec (snippets and syntax)
  • RailsTutorial
  • RubyCheckOnSave
  • RubyTest
  • Sass
  • SideBarEnhancements
  • SideBarGit
  • Simple Rails Navigator
  • SublimeBlockCursor
  • Theme - Soda

Settings

Find the full spec of config options via Sublime Text 2 > Preferences > Settings - Default. Modify via Sublime Text 2 > Preferences > Settings - User (which brings up ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/User/Preferences.sublime-settings for you to edit) or instantly via the menu Sublime Text 2 > Preferences. If you change settings via the menu, this config file is overwritten and reformatted!

Mine looks like this:

{
    "auto_complete_commit_on_tab": true,
    "bold_folder_labels": true,
    "color_scheme": "Packages/Color Scheme - Default/Slush & Poppies.tmTheme",
    "ensure_newline_at_eof_on_save": true,
    "font_size": 17,
    "highlight_line": true,
    "highlight_modified_tabs": true,
    "rulers":
    [
        80
    ],
    "save_on_focus_lost": true,
    "tab_size": 2,
    "theme": "Soda Light.sublime-theme",
    "translate_tabs_to_spaces": true,
    "trim_trailing_white_space_on_save": true
}

Here is another example.

File management and editor layout

Cmd+p (which is also mapped to cmd+t) brings up the Go To File palette. Goto Anything lets you navigate files swiftly using fuzzy matching. A cautionary note: when you open a file via the standard Mac osx file open dialog (cmd+o), itdoes not show hidden files by default and there is no visible option. So if you would like to open a file say in /etc, you run into trouble: Use Cmd+shift+. in the dialog to show these hidden files and folders.

One can toggle open/close sidebar with cmd+(k+b) (yes, I mean cmd+k followed by cmd+b, not too transparent…). Or you can get rid of stuff that gets in the way of coding with a special feature: View > Enter Distraction Free Mode (Ctrl+shift+cmd+f).

Projects group sets of files and directories as a unit. Typically, you just open a directory and save it as a project. One can switch between projects with Cmd+backtick.

Use View > layout for split panes (e.g., Cmd+shift+2 splits the editor pane vertically into two columns each having a group of files. You can switch to the first from left focus group with Ctrl+1. Similarly to switch between files within a group with Cmd+1/2/3/... or step left/right with Cmd+Alt+Arrow.

Console opens with Ctrl+backtick.

Painfully to me, I am already missing Rubymine's vertical tabs (tab titles are on the left, next to project sidebar). Is there a way to do this?

Ruby and Rails

Testing

There is a RubyTest plugin available for running your unit / rspec / cucumber tests.

  • Cmd+Shift+T to run all specs
  • Cmd+Shift+R to run the current spec (if the spec file has the focus)
  • Cmd+Shift+E to run the latest test run, this is super convenient since you do not have to jump to the spec from a class file.

RubyTest also supports rvm as well as rbenv for detection of right rubies. The package settings are in ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/RubyTest/RubyTest.sublime-settings. To use rvm, set:

"check_for_rvm": true,

First I had some trouble using it with rvm but with current rvm versions it seems to work all fine. The plugin readme says:

RVM / RBENV auto detect (thx to @bronson) - feature is disabled by default, but if you enable it then be sure that your settings file is configured to use bundle exec (refer to https://github.com/maltize/sublime-text-2-ruby-tests#bundler-support)

but Michal Papis of rvm:

"bundle exec" is required when you use Gemfile/bundler and do not use rubygems-bundler … but it should be installed by default with rvm

Indeed all commands seem to work just fine out of the box without prepending the tedious bundle exec everywhere.

Alternatively, you can use custom commands as described in this codeclimate post:

I started with this, but RubyTest looks less adhoc and more promising to maintain because it is a managed package.

Ruby and Rspec bundles builder

This blog post describes ways to modify the ruby and rspec bundles' builders to respect rvm. Note that it also mentions the same trick for the Rubytest plugin but, as you see above, that has since been supported.

~/Library/Application\ Support/Sublime\ Text\ 2/Packages/Ruby/Ruby.sublime-build:

{
  "env":{
      "PATH":"${HOME}/.rvm/bin:${PATH}"
  },
  "cmd": ["rvm-auto-ruby", "$file"],
  "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
  "selector": "source.ruby"
}

Cmd+b invokes the builder which will use rvm-auto-ruby to run the file. This will then use the settings in the .rvmrc file, running the specific ruby of choice. If no project-specific .rvmrc exist, rvm falls back to default ruby - as you'd expect.

The same can be applied to the Rspec bundle (which does not ship with Sublime, it has to be installed). Modify the contents of ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/RSpec/RSpec.sublime-build:

{
  "env":{
      "PATH":"${HOME}/.rvm/bin:${PATH}"
  },
  "cmd": ["rvm-auto-ruby","-S", "bundle", "exec", "rspec", "-I ${file_path}", "$file"],
  "file_regex": "# ([A-Za-z:0-9_./ ]+rb):([0-9]+)",
  "working_dir": "${project_path}",
  "selector": "source.ruby",

  "windows":
  {
      "cmd": ["rspec.bat", "-I ${file_path}", "$file"]
  }
}

Changing "cmd" to run rvm-auto-ruby -S bundle exec rspec instead of just rspec will use the ruby from RVM to run the specs, exactly as the RubyTest package.

Editing

Autoformat, reindent, prettify, tidy

Although you can reindent a single line: Edit > Line > Reindent, it does not even have key shortcut and cannot generalise to a region or whole file. Well yes, this is a major deficiency of Sublime: generic reformatting/codetidy linked to the same key across bundles is sadly missing, instead one needs to install beautifying plugins. For ruby though you can install the package beautifyRuby which links reformatting to Ctrl+Cmd+k. I added to this package functionalities. Now it supports erb template formatting using Paul Battley's htmlbeautifier gem(gedit erbbeautifier could be an alternative). It also offers a pre-save hook: your ruby and erb files will be reformatted automatically before saving. To activate this feature, set in your BeautifyRuby.sublime-settings:

"run_on_save": true,

For generic html autoformatting, there's a suite of options:

  • Once you have the Tag plugin installed, the applicable command is "Indent Tags on Document".
  • There is also a libtidy-based sublime plugin HTMLTidy. it is targeted at php, uses a webservice but most sadly does not support erb templates.
  • TidyHTML5 plugin is based on tidy-html5. this one is only triggered on .html extension and complains about erb.
  • HTMLPrettify seems most popular and can handle html, css and js. you need node.js installed in order to run the beautifier.

Keyboard

To my great pleasure apart from usual editor key combinations, Sublime supports some of my favourite Emacs bindings, notably:

  • kill line starting from cursor Ctrl+K and puts it to the 'killring'=secondary clipboard
  • yank (=paste from killring) Ctrl+Y

Read more on Key bindings here and a draft reference (incomplete and maybe incorrect :) on keyboard shortcuts on OS-X.

Autocompletion

Extending Sublime

Sublime is fairly compatible with Textmate bundles with the notable exception of commands. Sublime enables users to easily add features, comes with an embedded Python interpreter to test API calls. Extending Sublime via commands, macros, snippets, plugins is documented here. One can write custom commands (and bind them to keyboard shortcuts) by dropping Python class files in ~/Library/Application Support/Sublime Text 2/Packages/User and then binding them from Default (OSX).sublime-keymap in the same directory.

Resources

Comments