I’m in the process of upgrading a rails app from 2.1 to 2.3, and 2.3 wants me to refresh some of the gemspecs for my vendored gems. Unfortunately, when I run rake gems:refresh_specs I get the dreaded:

rake aborted!
can't activate , already activated json-1.1.9

I was able to refresh the spec in question outside of rake with (in the console):

>> Rails::GemDependency.from_directory_name('vendor/gems/gem_name-0.1.0', false).refresh

Hopefully that helps someone else out.

The Quest

Like most programmers, I type a lot – many hours a day, most days of the week. The keyboard is the primary conduit of my creative expression most of the time, whether I’m writing code or constructing elaborate stories to impress friends, clients, or co-workers (aka email/chat/this blog). For the last couple of years, I’ve been mildly obsessed with making that conduit more efficient. I’ve tried several different keyboards and entirely new keyboard layouts.

I stopped the keyboard search with the Kinesis Advantage – it works really well for me, and is the easiest keyboard for touch typing that I’ve ever used. But the keyboard layout search continued. The productivity hit during the learning period for Dvorak or Colemak was too great, and I quickly slid back to Qwerty.

I could type as fast as I wanted in Qwerty, so I tried to figure out what was really bugging me about my typing. I realized it was the shift key – I was frustrated with the high percentage of characters I typed that involved shift. I primarily code in Ruby, which uses ‘_’ much more often than ‘-’ (about 14 times more often), ‘:’ more than ‘;’ (about 78 times more often!), and ‘{}’ more than ‘[]‘ (or so I thought – more on that later).

I then decided to create a custom keyboard layout that would reduce the need for the shift key when coding. My goals were:

  • no remapping of the letter keys, since my muscle memory knows where they all are
  • remap commonly used symbols to be available without the shift key
  • be easy to learn, so no remapping characters to new keys

Using the Ukelele keyboard layout editing tool (for MacOS), I played around with some layout ideas before settling on the one I’ve been using since May 2009.

The Layout

Since I mostly code in Ruby, and mostly use symbols in code vs. email/chat/etc., I remapped the shifted symbols I used more often.
I ’shift-swapped’ (meaning the symbol you get with or without the shift key depressed are reversed) the following character pairs:

  • { [
  • } ]
  • | \
  • ~ `
  • : ;
  • _ -

I assumed that I used most of the symbols on the top row number keys more than I used the numbers, so I shift-swapped the 1 – 0 number keys with the corresponding symbol. If caps-lock is on, number keys revert to normal, but all of the other symbol keys remain swapped (meaning when caps-lock is on, pressing the ‘1′ key will give you a 1, but pressing the ‘[' key will give you a {). Since the Kinesis keyboard does not have a separate keypad, this makes entering number sequences easier.

The caps-lock key has been moved to the f1 key, and I use the original caps-lock as a control key (for Emacs). This mapping can't be done by Ukelele, since it cannot remap function or modifier keys, so I did this using the remapping functionality in the Kinesis keyboard itself.

Analysis

After six weeks or so of using the new layout, I decided to analyze a large ruby codebase to see what my shift pair ratios actually were (something I should have done before creating a new layout). Using this script, I got the following results:

Analyzed 457 files, 25060 lines
` ~     25     58  2.320
1 !   1161    713  0.614
2 @    564   2700  4.787
3 #    416   1914  4.601
4 $    264     55  0.208
5 %    359    303  0.844
6 ^    257     44  0.171
7 &    152    226  1.487
8 *    176    115  0.653
9 (    196   4479  22.852
0 )   1761   4485  2.547
- _   1559  21837  14.007
[ {   1385   1304  0.942
] }   1396   1306  0.936
\ |    144   1480  10.278
; :    108   8446  78.204
= +   5588    729  0.130
‘ "   5585   3909  0.700
, <   4737    791  0.167
. >  10257   2067  0.202
/ ?   1077   1054  0.979

Columns one and two are the shift pairs. Columns three and four are the occurrence counts for each character in the pair. The last column shows the ratio of the second character (normally shifted) to the first character (normally not shifted). So a higher number in that column indicates an advantage to swapping the shift pair.

I looked at the shift pairs I had swapped, along with the other symbol shift pairs that I did not swap (the last five lines above). There are some big wins here with my current remapping, along with some loses. The '[]'/'{}' swap was a small mistake - looks like I access elements of collections slightly more often than I define inline blocks or explicit hashes (which is kind of obvious in hindsight. In fact, on reflection I would think that collection access would happen considerably more often than inline block creation). And some of the number key remaps are big loses based on the ratios, but the lowest ratio pairs there have generally low volume. After this analysis, I didn't undo any of the remappings, though I should have reversed (and still should reverse) the bracket/brace swap.

Usage

The name of this layout is 'rubyist'. If you are interested in giving it a try, download the MacOS keylayout file here, and put it in ~/Library/Keyboard Layouts/.

I don't expect this layout to work well for everyone, or really anyone other than me. I do think all of us could benefit from evaluating the text we type the most, and seeing if some keyboard layout tweaks could make us more efficient. If you do want to give your own layout a try, check out these platform specific tools:

pomodoro_status

For the last few months, I’ve been playing with the pomodoro technique to manage my time and stay focused on the task at hand. It works best for me when I’m stressed and have an overwhelming workload. It helps me focus on the immediate task, and not get distracted too much by all of the other stuff I need to do.

One issue with managing the technique is keeping interruptions to a minimum. When I start a pomodoro, I’ll quit email, twitter, and chat. But we are a distributed team, and I work from home 95% of the time. I want to let the rest of the team know I’m around, but also let them know that I’m in a pomodoro, and to only interrupt in emergencies. Since we primarily use Campfire to communicate, I set up a ‘Status’ room there that allows us to post what we are up to/where we are at/etc. Its not only useful for pomodoro updates, but also ‘off to lunch’, ‘gone for the day’, etc. (And here is a third sentence that ends in etc.) But manually entering those status updates means they won’t happen. So I wrote a simple update script using the lovely tinder gem. It consists of two files – the script itself:

and the config file (~/.campfire_status):

But pomodoro status updates still require a manual step to run the script. Enter Pomodoro, a MacOS pomodoro client by Ugo Landini. His client allows integration with growl, twitter, and applescript. So I added the following applescript snippets to update the status for me:

A couple of gotchas I ran in to:
* the Pomodoro app does not allow copy & paste in the applescript text areas, making it a bit of a pain to enter
* the Pomodoro app also has a file selector next to each applescript text area, but I could not get it to recognize the saved applescripts
* the Campfire API seems to ignore requests from users that are currently logged in(?), so the status updates come from another account (in our case, we have a ’service-bot’ account that posts messages from other services). That’s why there is a USER_NAME setting that is displayed with the message.

I just released a stupid simple plugin based on the idea behind Coda Hale’s rails_environments plugin.

This plugin adds the following functionality to the Rails module to help with determining the current enviroment:

  >> Rails.environment       # a convenience alias to Rails.env
  => "development"
  >> Rails.development?
  => true
  >> Rails.not_development?
  => false
  >> Rails.production?
  => false
  >> Rails.not_production?
  => true
  >> Rails.test?
  => false
  >> Rails.not_test?
  => true

Not only does it provide env? and not_env? methods for the standard environments, it also provides those methods for any environment you define in config/environments/ (in fact that is how it learns about all of the environments, including the standard three). So if you define new environments in config/environments/ they will be picked up automatically.

Install with: script/plugin install git://github.com/tobias/rails_habitat.git

It lives on github.

Edit: see David’s comment below for the built in way to do this (in Rails >= 2.2).

We use Campfire for internal communication, and I’ve lately been pushing notifications there for all to see (Zendesk ticket updates, git repo pushes, etc). We decided it would be useful for the support team to know when a deployment occurs. I googled a bit to see if anyone had shared a Capistrano recipe, and did not find one. So I’m sharing mine.

Using the tinder gem, its super easy:

Enjoy!

I extracted how we are doing Zendesk remote authentication from an app at Dealer Ignition, and stuck it in a small gem for your enjoyment. You can find it on GitHub.

Installation and Setup

Install:

gem install tobias-zendesk_remote_auth

Setup:

You will need to give the gem your token and authentication url, perhaps in an initializer:

  Zendesk::RemoteAuth.token = 'YOUR-TOKEN'
  Zendesk::RemoteAuth.auth_url = 'https://yourcompany.zendesk.com/access/remote/'

and config the gem in environment.rb (if using rails):

config.gem 'tobias-zendesk_remote_auth', :lib => 'zendesk_remote_auth', :source => http://gems.github.com'

Usage

Mixin the Zendesk::RemoteAuthHelper module wherever needed, then call:

  zendesk_remote_auth_url(:name => 'user name',
                          :email => 'user email',
                          <optional params>)

This will return a url you can redirect the user to to log them in to your zendesk account.

As a convenience, you can pass a user object to zendesk_remote_auth_url:

  zendesk_remote_auth_url(user)

This user must respond_to? :name and :email, and its :id will be used as the :external_id (making it useless with user objects that return an ephemeral object_id, but works well with ActiveRecord and the like). If the user object responds to :zendesk_organization, that will be used as the :o rganization for the call.

This method will generate and include the hash of the parameters for you if necessary.

Example Auth Controller

Here is an example controller that handles login and logout for zendesk:

  # Uses restful-authentication style auth. 
  # 
  # Define the following in routes.rb:
  # map.with_options :controller => 'zendesk_auth' do |zd|
  #   zd.connect '/zendesk/authorize', :action => 'authorize'
  #   zd.connect '/zendesk/logout', :action => 'logout'
  # end
  class ZendeskAuthController < ApplicationController
    include Zendesk::RemoteAuthHelper
 
    skip_before_filter :login_required, :only => :logout
 
    def authorize
      redirect_to zendesk_remote_auth_url(current_user)
    end
 
    def logout
      redirect_to logout_url
    end
 
    protected
    def login_required
      if !logged_in?
        flash[:notice] = 'You must log in to access the support site.'
        store_location
        redirect_to login_path
      end
    end
  end

As an app grows, so does the amount of files in app/models. Here is a simple tip to help reduce the clutter: move mailers, observers, and sweepers out of app/models into app/mailers, app/observers, and app/sweepers, respectively. For rails to still load them, you will need to modify config/environment.rb:

  # clean up app/models a bit
  %w{mailers observers sweepers}.each do |dir|
    config.load_paths << "#{RAILS_ROOT}/app/#{dir}"
  end

As a bonus, you can now automatically record your observers with ActiveRecord instead of having to add them individually in environment.rb:

  config.active_record.observers = Dir.glob("#{RAILS_ROOT}/app/observers/*.rb").collect do |filename|
    filename.split('/').last.split('.').first.to_sym
  end
One issue with this reorganization is that the generators will continue to create mailers, observers, and sweepers in app/models. For me, that is not a big deal – I don’t create them often, and manually move them after generation. I suspect it would be trivial to adjust the generators to use the new path, but have not looked in to it.

In my youth (aka when I was 30) I ran a marathon, and had not run since until today.

My entire life, running is something I would do for a while and really enjoy, only to walk (ha!) away from it for a while. Life would get it the way (I would move, a new job would keep me too busy, {insert any other excuse here}). But then I would remember that I enjoyed it, and lace up again.

This latest break of five years since the marathon has been the longest. I have been considering running again for the last few weeks, but have had reservations: the narrow road I live on isn’t safe for running, I’m too busy with work and a new baby, {insert any other excuse here}. So when a friend called me up and asked me if I wanted to run the Outer Banks Marathon in November, I decided to go for a trial run this morning.

But first, to prepare! I need shoes, and shorts, and a fancy shirt; running socks, a gps, a smaller ipod, a runners log book. A couple of days ago I read Chad Fowler’s article on this exact situation: where we plan a new hobby, and instead of just doing it, we buy all the tools we need as a way to feel like we are making progress, instead of just doing it. I know I’ve done that – in my recent quest to learn to play guitar, I’ve accumulated: a guitar, a gig bag, a stand, two tuners, a capo, and a stack of books, but I don’t yet really know how to play. After reading Chad’s article, I decided to be more mindful of that tendency. I resisted the urge to buy anything for running, at least until I’m actually doing it on a regular schedule (and then all I’ll really need is a new pair of shoes). Last night, I gave in to the urge and started writing a Sinatra based running log application. I told myself I was doing it to learn Sinatra better, and to learn MongoDB, but did I really do it to feel like a runner?

I just re-released my server_remote plugin as a gem server_remote on github. I converted it to a gem to make it easier to use in multiple apps, and to make it easier to update (see here for the blog entry on the (now obselete) plugin).

It is a gem that provides support for running commands on remote server. Once set up, it provides commands via script/remote:
  • remote shell – same as ssh’ing to the server (this is the default command, so it can be called with just remote)
  • remote console – executes a script/console on the server
  • remote logtail – executes tail -f log/<environment>.log on the server
  • remote cmd <some command> executes command on the server, displaying the result. It cd’s to the remote app root first.
  • remote scp <local_file> :<remote_file> provides scp. Prefix remote files with ‘:’
Configuration is in config/server_remote.yml, and is grouped into profiles.

Here is the output of remote usage:

Executes commands on a remote server over ssh. Configuration is in:
/Users/tobias/customers/DealerIgnition/dealer_ignition/script/../config/server_remote.yml
 
You can override the profile used with -p profile. The default profile is: app
 
Learn more in the readme:
/opt/local/lib/ruby/gems/1.8/gems/tobias-server_remote-0.2.0/lib/server_remote/../../README.textile
 
remote commands are:
 
    DEFAULT COMMAND   shell
 
    cmd               executes an arbitrary command on the server after a cd to the app path
    commands          List all 'remote' commands
    console           executes remote console
    help              Provide help documentation for a command
    logtail           executes remote tail -f on the log
    scp               copies files over scp (prefix remote files with ':')
    shell             executes remote shell
    usage             prints usage message
 
For help on a particular command, use 'remote help COMMAND'.

It uses remi’s simplecli gem.

I plan to add other commands as needed, or you can open up Remote::Commands and add your own.

Installation

You will need to install the gem (only once), then setup any apps where you want to use it.

  sudo gem install tobias-server_remote --source http://gems.github.com/
  server_remotify path_to_app

I recently published a gem that provides credit card validation. It is basically a ruby port of the javascript credit card validator by Thomas Fuchs (madrobby).

Usage:

  CreditCardValidator::Validator.valid?('1111 2222 3333 4444')
 
  # allow test numbers to be valid (for development) 
  CreditCardValidator::Validator.options[:test_numbers_are_valid] = true
  CreditCardValidator::Validator.valid?('1111 2222 3333 4444')
 
  # limit the card types you allow
  CreditCardValidator::Validator.options[:allowed_card_types] = [:visa, :mastercard]
  CreditCardValidator::Validator.valid?('1111 2222 3333 4444')

Supported card types:

  :amex, :discover, :diners_club, :master_card, :visa

Whitespace is stripped from the number automatically.

The following things are tested:

1. does the luhn validation code add up? (see http://en.wikipedia.org/wiki/Luhn_algorithm)
2. does the number range and length seem right? (see http://en.wikipedia.org/wiki/Bank_card_number)
3. is it one of several well-known test numbers?

Note: this only validates that the number is of a valid format, it does not check if it is an actual credit card number. You will need to talk to your payment gateway to learn that.

You can also use the validator to learn about the type of the card:

  # gives the type back as a string (visa, master_card, etc)
  CreditCardValidator::Validator.card_type(number)
 
  CreditCardValidator::Validator.is_visa?(number)
  CreditCardValidator::Validator.is_master_card?(number)
  # etc. - works for all of the supported card types
 
  CreditCardValidator::Validator.is_allowed_card_type?(number)

To Install:

  gem install tobias-credit_card_validator --source http://gems.github.com

The source is available on github