Duplo

Building Blocks & Learning Experiences

I ran across a really obscure and subtle bug in Ruby 1.9, which was triggered by RSpec including a module for the purpose of altering RSpec::Mock objects before they’re serialized to YAML.

I was attempting to update a work project from REE 1.8.7 to MRI 1.9.3. Some of the tests were failing with a SystemStackOverflow: stack level too deep error while trying to save an ActiveRecord (AR) model. The stack traces were completely useless, they could only lead me to the save! call in the test.

Using the debugger proved exceedingly difficult, because as of AR 3.x, callbacks were re-written to use heavy metaprogramming, and it doesn’t take long before the debugger has no idea which line of code its on anymore.

I tried a number of things, including disabling callbacks, observers, and serialized attributes. I increased the maximum stack size, ran the tests in different orders, ensure the databases were cleaned before and after each test, and a number of other things. The tests always failed with 1.9, but passed with 1.8.

When none of those things worked for the primary model, I started to do the same for models referenced as belongs_to relations of the primary model. Sure enough, one of them was indeed the culprit. I began the process again, but this time on the secondary model. I was able to quickly narrow it down to one of the secondary models’s serialized attributes. A simple ActiveSupport::HashWithIndifferentAccess (HWIA) was to blame. Whenever I tried to serialize it, kaboom! I was able to further narrow it down to the first key-value pair, ("async", nil). Reproducing this same HWIA in the console did not yield a crash, however.

Using pry, I compared the output of ls -v for the nil value in the console, versus the nil value in the RSpec test. What I noticed, was that the to_yaml methods were attributed to different sources. In the console, to_yaml came from Object, while in the RSpec test, to_yaml came from RSpec::Mocks::Serialization::YAML.

Searching Google, I quickly found a workaround, use the older YAML parser, syck, instead of the new default of psych:

YAML::ENGINE.yamler = "syck"

But syck has its own issues, and besides, there’s no reason why this shouldn’t work, the HWIA wasn’t cyclical at all. I kept looking, then eventually I found it.

https://github.com/rspec/rspec-core/commit/622a4b7ac41e0ab6a4786070cca3ff866b72b57c

More googling led me to this:

https://gist.github.com/myronmarston/845896

End result? Upgrade RSpec to a version >= 2.6.

Then I searched some more, to see if the core ruby folks know about this? Yep, they do:

http://bugs.ruby-lang.org/issues/3351

It’s slated to be fixed in 1.9.4, if such a beast is ever released.

Thanks to my co-workers at LMP, and the folks on the URUG mailing list for helping me out along the way.

Rxvt-unicode (aka urxvt) has been my terminal of choice in Linux these days. Since I like to use the keyboard as much as possible, I found it frustrating that I couldn’t paste from my clipboard into urxvt without having to use the middle mouse button.

I searched for a solution to this problem, and found urxvt-perls by Bert Muennich. His clipboard plugin for urxvt adds CTRL-v pasting to urxvt. It solved the problem perfectly.

Another great tool along these lines, is parcellite. It unifies your primary clipboard (those things you highlight with the mouse) with the copy clipboard (things you specifically use CTRL-c or Edit > Copy for). With parcellite running, you can click the “Copy URL to Clipboard” icon on Github, then ALT+Tab to your terminal, and type: git clone <CTRL-v> to clone.

I was having some trouble running rspec within Emacs. One of the gems in my Gemfile was pointing to a git repo, and as a result, bundle was shelling out through Emacs to check my revision using this method:

def revision_from_git
  if File.exists?(scope('.git/HEAD'))
   Dir.chdir scope(".") do
     `git rev-parse HEAD`
    end
  end
end

Since my git lives in a non-standard location, it was failing:

/Users/xxxxxxxx/.rvm/gems/ruby-1.9.2-p290@global/bundler/gems/compass-91a748a91636/lib/compass/version.rb:48:in ``': No such file or directory - git rev-parse HEAD (Errno::ENOENT)

Searching for a solution, I found a page in the EmacsWiki that dealt with this issue, but I didn’t care for any of the solutions there. What I went with was to open ~/.MacOSX/environment.plist with the Property List Editor, and add the path to my git executable to the PATH variable therein. I then had to reboot. The reboot seems to be the only way to get launchd to re-read this file. I launch Emacs via Spotlight, and so it is started by launchd behind the scenes. I tried using launchctl setenv first, as mentioned in the EmacsWiki, but that didn’t seem to work, I’m not sure why.

With the PATH variable set, rspec-mode, and rvm.el loaded, I was able to successfully run my specs from within Emacs.

If you happen to have a <select> tag with its multiple attribute set, you can unselect them in Cucumber by adding this step:

When /^(?:|I )unselect "([^"]*)" from "([^"]*)"$/ do |value, field|
  unselect(value, :from => field)
end

When using tmux in Terminal.app with the TERM preference set to xterm-color causes some weird line wrapping behavior. Images speak louder than words here:

Just before the weirdnessJust before the weirdness

The weirdness beginsThis blank line is the weirdness, it’s really disconcerting when typing a long command, or when using readline to look through previous commands.

Continuing weirdness...The weirdness continues…

And after a CTRL-l we're fine againBut a CTRL-l will help ease our pain.

The weirdness seems to have something to do with being at the bottom of a terminal window. The problem is not exhibited at the top of an empty window.

A solution is to set your TERM value in Terminal.app to xterm.

The uservoice gem provides a nice easy way to integrate your Rails app with the UserVoice user feedback service. If you’re using Heroku to deploy your Rails app, there are two things that will provide speed bumps. The first is that, short of storing your UserVoice API key in your git repository, there’s no way to get it into your Rails app’s configuration. The second is that the uservoice gem lists rails as a dependency. Both can be overcome, and I’ll describe how.

Securely Passing Your UserVoice API Key To Heroku

In order to pass your UserVoice API key to Heroku without committing it in plain-text in your git repository we make use of Heroku’s config feature.

$ heroku config:add USERVOICE_API_KEY=<your api key> USERVOICE_USER=<your username>

This will make your UserVoice API Key and username accessible to your Heroku Rails app via ENV["USERVOICE_API_KEY"] and ENV["USERVOICE_USER"] respectively.

Now we simply need to get these values into the uservoice gem’s config/uservoice.yml configuration file. To do this, we need to add ERB support to the uservoice gem’s config loadermy pull request has been accepted, and this functionality is baked in to the uservoice gem as of version 0.3.1.

Now we can setup our uservoice gem configuration file like so:

uservoice_options:
  # required
  key: <%= ENV["USERVOICE_USER"] %>
  host: my_app.uservoice.com
  forum: my_app
  # optional
  showTab: true
  alignment: left
  background_color: "#f00"
  text_color: white
  hover_color: "#06C"
  lang: en

uservoice_api:
  api_key: <%= ENV["USERVOICE_API_KEY"] %>

Installing The Uservoice Gem To Heroku

Of course we need to add the uservoice gem to our .gems file. However, the uservoice gem lists Rails as a dependency. This means that when Heroku installs the uservoice gem, it will also install the latest version of Rails (2.3.8 at the time of writing). Heroku’s stack currently relies on Rails version 2.3.5, and having the two versions of Rails installed causes a clash. The solution is to add the --ignore-dependencies flag to the uservoice line of the .gems file. However, this means that Heroku won’t install uservoice’s other dependency, the ezcrypto gem. To work around that, we simply add ezcrypto manually, on it’s own line, to the .gems file. The lines that need to be added should look like this:

# <RAILS_ROOT>/.gems
ezcrypto --version '>= 0.7.2'
uservoice --version '>= 0.3.1'  --ignore-dependencies


While the version arguments aren’t strictly necessary, I’ve found it helpful to be explicit when specifying gems, to help alleviate issues caused by new versions of gems being released in the middle of my development cycle.

With those changes in place, you should be able to push your git repository to Heroku and receive all sorts of great user feedback.

This post is a reminder to myself, that when I upgrade my webrat gem, I need to replace its vendor/selenium-server.jar. If I forget, then Selenium Remote Control will most likely break because the version of selenium-server.jar included with webrat is old, and doesn’t support current versions of Firefox.

I’ve often been sad that there is no default keybinding for comment-region in Emacs’s ruby-mode. Eventually it annoyed me enough that I added one:

(add-hook 'ruby-mode-hook
	  (lambda ()
	    (define-key ruby-mode-map "\C-c#" 'comment-or-uncomment-region)
	    )
	  )

This assigns C-c # to comment the current region, or if the current region is already commented, it will uncomment the region.

But what about when there’s no region currently marked? It would be nice if emacs would (un)comment the current line. To do this, I took a page from DJCB at Emacs-fu.

(defadvice comment-or-uncomment-region (before slick-comment activate compile)
  "When called interactively with no active region, comment a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
	   (line-beginning-position 2)))))

Now with nothing marked, pressing C-c # will cause emacs to toggle commenting on the current line.

In case it isn’t obvious, one should add the abbove snippets to their .emacs file to gain their benefits.

Autotest-inotify is a gem that extends autotest to use Linux’s inotify to monitor changes to your source and test files, running the appropriate tests as files are modified.

By default, autotest implements filesystem polling to detect these changes. This can use a significant amount of CPU cycles1, and can impact battery life in laptops.

Through Linux’s inotify, autotest-inotify inserts callbacks into the underlying filesystem, which allows the filesystem to notify us when files we’re interested in have been modified. This allows autotest to sleep until inotify indicates a change has been made to one our files of interest, i.e. we don’t have to constantly poll the filesystem.

This work was inspired by Sven Schwyn’s work on autotest-fsevent, which extends autotest to use Mac OS X’s FSEvents system, as well as Alban Peignier’s work using the INotify gem. Where autotest-inotify differs from Schwyn’s work, is that autotest-inotify can be used in Linux, whereas autotest-fsevent uses FSEvent, which is Mac OS X specific. Autotest-inotify differs from Peignier’s work in that it offers a simpler gem-based installation, and it is less obtrusive to autotest’s methods for determining which files to watch for changes.

Source code for the autotest-inotify gem can be found at http://github.com/ewollesen/autotest-inotify. It is licensed under the MIT license. See the README for installation instructions.

  1. On one of my machines, ~25% of a single core’s cycles were spent polling the filesystem []

In the process of setting up metric_fu, I found that, one way or another, saikuro’s output wasn’t getting into the correct place. I’ll spare you the long story, and just show the config settings I had to put into my Rakefile to get things working:

config.saikuro = {
  :output_directory => "#{ENV["CC_BUILD_ARTIFACTS"]}/scratch/saikuro", 
  :input_directory => ["app\" --input_directory \"lib"],
  :cyclo => "",
  :filter_cyclo => "0",
  :warn_cyclo => "5",
  :error_cyclo => "7",
  :formater => "text", #this needs to be set to "text"
}
config.flay = {
  :dirs_to_flay => ['app', 'lib',],
  :minimum_score => 10, 
}


My changes in bold.