Ruby on Rails

Directory Conventions for Rack Middleware RubyGems

I just wanted to make a quick note about directory conventions for rack middleware gems. For all gems you should follow the convention of housing all of your code inside a single file and directory of the same name as your gem within lib, e.g.

$> ls -l ~/projects/timecop/lib drwxr-xr-x 5 john staff 170 Jan 14 20:31 timecop -rw-r--r-- 1 john staff 82 Jan 14 20:31 timecop.rb

The reason for this is related to how RubyGems hijacks Ruby's require method. When a gem is activated its lib/ folder is added to the load path. This means that anything inside that directory is now accessible via the require method. In order to avoid file naming collisions across gems, you must name these exactly the same as your gem. (see slides for I Don't Trust Your Code for a more complete discussions of this)

However, this is slightly different with rack gems. The convention for naming rack middleware is by using a dash, e.g. rack-rewrite. The convention for requiring rack middleware though is to replace that dash with a slash, e.g. require 'rack/rewrite'.

The convention I've adopted for structuring rack middleware within a gem is to include a file by the same name as the gem and a rack directory in lib/, and then to include the second part of the middleware name as a subdirectory under that.

~/projects/rack-rewrite (master) $> ls -l lib/ total 8 drwxr-xr-x 4 john staff 136 Apr 17 18:02 rack -rw-r--r--@ 1 john staff 22 Apr 17 18:02 rack-rewrite.rb

~/projects/rack-rewrite (master) $> ls -l lib/rack
total 8
drwxr-xr-x 3 john staff 102 May 13 11:09 rewrite
-rw-r--r--@ 1 john staff 827 Apr 17 18:02 rewrite.rb

This allows my users to use either require 'rack-rewrite' or require 'rack/rewrite'.

You've successfully subscribed to SmartLogic Blog
Great! Next, complete checkout for full access to SmartLogic Blog
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.