Duplo

Building Blocks & Learning Experiences

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.

When my wife recently pointed me to an article by Jim Weirich about Dependency Injection (DI), one of my first thoughts was, “how is this different from the Abstract Factory (AF) pattern?” So I did some searching and found a brief comment from Martin Fowler:

If you have multiple ways to construct a valid object, it can be hard to show this through constructors, since constructors can only vary on the number and type of parameters. This is when Abstract Factory Methods come into play, these can use a combination of private constructors and setters to implement their work. The problem with classic Factory Methods for components assembly is that they are usually seen as static methods, and you can’t have those on interfaces. You can make a factory class, but then that just becomes another service instance. A factory service is often a good tactic, but you still have to instantiate the factory using one of the techniques here.

Fowler’s objections with respect to static methods on interfaces are specific to java, and don’t apply in python or ruby, since neither have native interfaces. Yet I see DI used in both ruby and python, so I still feel like there has to be another difference.

Next I found some interesting thoughts at Stack Overflow, but none of the responses shed a clear light on the subject for me.

What finally got the light in my head to switch on, oddly enough, was an article by Jakob Jenkov. After reading Jenkov, I understood that both AF and DI are responsible for creating instances of objects. Furthermore, they both decouple the class requesting object creation from having to know any details about the created object that they’ll receive. Where they’re different, is that when AF is being used, the class desiring the creation of an object needs to know about—and send a message to—an AF, whereas with DI, the class desiring the creation of an object is simply handed that object during it’s own initialization. To put it another way, the object on which it relies is “injected” into it at its own creation. This is the inversion, that rather than the class needing to ask for an object to be created, it is instead handed the object.

Dependency Injection as compared with Abstract Factory.
Characteristic DI AF
Is responsible for instantiating classes? Yes Yes
Class needs to know details of the created object? No No
Class needs to explicity request creation of desired object? No Yes
Class is dependent upon the DI/Factory that creates objects on its behalf? No Yes

Now that the light was on, I re-read the first few references, and I found that may of them made more sense. Funny how that works.

There are a number of different ways to handle custom error pages in rails. Most use rails’s rescue_from method. This approach allows your error pages to be dynamically rendered in response to errors.

The way I see it, if my site has just encountered an error, I want to immediately go into damage control mode. Do I want to risk dynamically generating an error page? No, not at all. There could be an error in the page rendering that will cause another error when I try to render the error page. Not an ideal situation to say the least. It’s much safer to serve up previously generated static content.

While rails does come with a default, static, error page, said page is largely unstyled, and contains no links to help the user get back to what they were doing. I feel that it’s bad enough that I have to display an error to the user; leaving them with nowhere to go, looking at a jarring, or even ugly, error page isn’t going to make them the happy users that we all want.

Lastly, I don’t want to have to remember to keep the site’s error pages up to date with the latest layout and style.

To summarize, I want static error pages, rendered using rails’s ActionView, and I want them updated automatically any time the site’s style or layout changes.

To accomplish these goals I wrote a rake task and a capistrano recipe. The rake task visits the site, collects the rendered error pages, and stores them in the <RAILS_ROOT>/public directory, where rails will automatically look for them when errors occur. Here’s the rake task:

desc "Generate static error pages (404 and 500)"
task :generate_static_error_pages => [:environment] do
  require "console_app"

  urls_and_paths.each do |url, path|
    r = app.get(url)
    if 200 == r
      File.open(Rails.public_path + path, "w") do |f|
        f.write(app.instance_variable_get(:@body))
      end
    else
      $stderr.puts "Error generating static file #{path} #{r.inspect}"
    end
  end
end

def urls_and_paths
  [["/static/404_not_found", "/404.html"],
   ["/static/500_internal_server_error", "/500.html"],]
end

The capistrano recipe simply runs the rake task each time the application is deployed. Here’s the recipe:

desc "Generate static error pages"
task :generate_static_error_pages, :except => {:no_release => true} do
  run "cd #{current_path} ;
       RAILS_ENV=production rake generate_static_error_pages"
end


I’ve instructed capistrano to execute this recipe each time I deploy my application by using one of capistrano’s many handy callbacks:

after "deploy:symlink", "generate_static_error_pages"

The result is that I have consistently styled, static error pages, that are updated automatically each time I deploy my application.

I found a way to make e17 work with the GNOME Keyring Daemon (GKD), so that I do not have to manually add my ssh keys to ssh-agent every time I login.

I didn’t discover the method myself, but I was on the right track, which led me to this Ubuntu bug report, which contains a successful workaround:

# in ~/.profile
if [ -n "$GNOME_KEYRING_PID" ]; then
    eval $(gnome-keyring-daemon --start)
    export SSH_AUTH_SOCK
fi

The bug report goes into detail, but basically the issue seems to stem from some out of order initialization of ssh-agent, ~/.profile, and the GKD, perhaps with e17′s lack of support for xdg autostart directives.

I was able to search out the bug report after a lot of comparing the output of ps xa and export while logged in via e17 and comparing it to the same from within GNOME. The output of the latter showed two different SSH_AUTH_SOCK formats:

# gnome
SSH_AUTH_SOCK="/tmp/keyring-HvW1Yb/socket.ssh"
# e17
SSH_AUTH_SOCK="/tmp/ssh-RMKCQa4949/agent.4949"

This gave me a hunch that my SSH_AUTH_SOCK was coming from ssh-agent, rather than from GKD. A google search for the terms “pam SSH_AUTH_SOCK” then turned up the bug report above.

In comment #8 of said bug report, Mikel Ward mentions that in xfce4, it’s possible that the GKD’s SSH_AUTH_SOCK is being overwritten by an incorrectly guarded call to ssh-agent in /etc/xdg/xfce4/xinitrc. e17 doesn’t have any such initialization (of which I’m aware), so I presume that my SSH_AUTH_SOCK stems from ssh-agent being called as part of /etc/X11/Xsession.d/90x11-common_ssh-agent, though admittedly I’ve done no work to confirm this hypothesis.

Not too long ago, ATI dropped support for my video card (ATI Radeon X1950XT) from the FGLRX driver.  When this happened, E17 reverted to mirroring my two monitors.  GNOME, for whatever reason, seemed to work just fine.  For a while I just worked in GNOME, but eventually I got curious, and decided to determine what was up with E17.  Since repeated web searches yielded next to nothing, I figured it had to be something weird with my system.  It took me a while, but I finally figured out how to turn dual head back on the way I wanted.  It all boils down to this one handy command:

$ xrandr --output DVI-0 --mode 1600x1200 --pos 0x0 --output DVI-1 --mode 1600x1200 --pos -1600x0

This command sets the resolutions for each of my two identical monitors, and sets the position of DVI-1 (which happens to be “on the left”) to be 1600 pixels (or one screen’s worth) to the left of DVI-0 (the monitor on the right).

I’m reasonably certain that the gnome-display-properties command basically just does the same thing, but for some reason it was ineffectual when being run from within E17.

… it has function scope.  Okay, I get that, but apparently I hadn’t totally wrapped my head around just what that means.  In essence, it means that all variables that have a declaration in the function, are declared, regardless of whether or not the line of code which declares them would be executed.  Given the following code:

var foo = "bar";

function test() {
  console.debug("foo is (1st time)" + foo);
  if (false) {
    var foo = "baz";
  }
  console.debug("foo is (2nd time)" + foo);
}

Your console will show something like this:

foo is (1st time) undefined
foo is (2nd time) undefined

Which is a little weird since the local declaration of foo was never executed.  A quick search didn’t turn up any promising hits, but I imagine that there must be a preprocessing step that executes all variable declarations before the function is run.  The very similar function below (diffs in bold):

var foo = "bar";

function test() {
  console.debug("foo is (1st time)" + foo);
  if ("undefined" == typeof(foo)) {
    var foo = "baz";
  }
  console.debug("foo is (2nd time)" + foo);
}

Yields:

foo is (1st time) undefined
foo is (2nd time) baz

A more intentional use is probably (diffs also in bold):

var foo = "bar";

function test() {
  console.debug("foo is (1st time)" + foo);
  if ("undefined" == typeof(foo)) {
    foo = "baz";
  }
  console.debug("foo is (2nd time)" + foo);
}

Which has output:

foo is (1st time) bar
foo is (2nd time) bar

So this isn’t anything groundbreaking, or even weird.  It’s clearly defined1, and discussed2, but the consequences eluded me for about an hour last night.  Hopefully by writing this article, I’ll remember for next time.

  1. http://docstore.mik.ua/orelly/webprog/jscript/ch04_03.htm#jscript4-CHP-4-SECT-3.1 []
  2. http://stackoverflow.com/questions/1711173/declaration-for-variable-in-while-condition-in-javascript []