Rails application.rb Recommendations


Today's post is going to be short and sweet. Because I find myself using a few settings in almost every single Rails app's config/application.rb, I want to share them with you, along with the rationale for each.

So, here are the settings I use and recommend:

# config/application.rb

config.generators do |g|
  g.assets = false
  g.helper = false

config.action_controller.include_all_helpers = false
config.active_record.schema_format           = :sql

First up, generators: I absolutely hate the cruft that Rails creates by default when I generate a new controller. I almost never want an empty javascript, stylesheet, or helper file, but I always want an empty test file. While these empty files might be useful to remind a new developer that they can use them to organize their code, once you've developed a few Rails apps, they are just noise until you need them.

Speaking of organizing code, you might not be aware of this, but for years now, all helpers have shared the same namespace by default. At one point, this was an obvious line you could remove in your ApplicationController, but later, it was baked into ActionController::Base. Your ProductsHelper module is available in product views, of course... but it's also available in views for posts, comments, widgets, honey badgers -- anything, anywhere, can access all helpers. This bears repeating: Helpers exist by default in a giant global namespace for all views.

This won't bite you until your app reaches a certain size or a certain number of developers, but at some point, you'll end up with an obscure error that doesn't show up in development, just production. You'll track the root cause down to two helper files containing a method with the same name. The order in which the helper modules are being autoloaded in production will determine which implementation for the method is being used -- last one wins.

This simple configuration line will allow common sense to once again prevail: ProductsHelper methods will be used for product views, but honey badger views won't have access to them. You can still add shared helpers to ApplicationHelper, or explicitly include helper modules with include.

Lastly, if you're doing anything remotely interesting with your database, you're going to find the default schema.rb dump format to be too lossy for your needs. Setting the schema_format to :sql will create a db/structure.sql file instead of the db/schema.rb file normally generated after a migration.

Anyway, these are my must-have application.rb settings. What are yours?

comments powered by Disqus