Automatic Per-Controller CSS in Rails

January 1, 2010 by alex

This is a simple method I’ve been using to automatically include controller- specific stylesheets. If you have app/controllers/users_controller.rb, then public/stylesheets/users.css will be included automatically if it exists. I’m sure this has been done before, but here’s my take on it.

# app/helpers/application_helper.rb
module ApplicationHelper
  def controller_stylesheet
    controller_name = controller.controller_name
    if File.exists?( "#{Rails.root}/public/stylesheets/#{controller_name}.css" )
      stylesheet_link_tag( controller_name )
    end
  end
end
<!-- app/layouts/application.html.erb -->
<html>
  <head>
    <%= controller_stylesheet %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>
☙ ☙ ☙