Fork me on GitHub

A GitHubby config.gem hack

2009-02-07 (ruby, rubygems, rails, github)

I love using gems from my Rails apps, and have been an outspoken proponent for gem plugins from the beginning (you won’t find any vendor/plugins in my newer apps at all).

I also love GitHub, but lines like this, over and over in my environment files, just annoy me:

config.gem 'username-foo', :lib => 'foo',
                           :source => 'http://gems.github.com'
config.gem 'username-bar', :lib => 'bar',
                           :source => 'http://gems.github.com'

So, here’s a quick little hack. It could be smarter, but it works.

module GitHubbyGems

  def gem(name, options = {})
    if options[:github]
      default_options = {:lib => name.split('-', 2).last,
                         :source => 'http://gems.github.com'}
      options = default_options.merge(options)
    end
    super(name, options)
  end

end

Rails::Initializer.run do |config|
  # ...
  config.extend GitHubbyGems
  config.gem 'haml'
  config.gem 'right_aws'
  config.gem 'thoughtbot-paperclip', :github => true
  config.gem 'mojombo-god', :github => true
  # ...
end

Enjoy.

Updates

James Bebbington likes an API that supports something like:

config.gem_source :github => 'http://gems.github.com'
config.gem 'foo', :source => :github

… and I agree that’s far less of a special-case hack.

Since what we really want to do is affect the configured Rails::Gem::Dependency (Configuration#gem just passes on the options to initialize one), that’s probably what we would really want to modify — and of course an old with_options-style approach would work, too.

Let’s keep in mind though, that in reality GitHub is a very special case (specifically, the gem naming scheme is), and since we’re talking about a handful of lines per configuration, it’s probably not worth it (write a text editor snippet instead, or just copy-paste).

But it’s a fun little hack.

Discussion