Theming in Rails 2 and Rails 3
On a fairly recent project, I needed to be able to theme an application easily. What I am going to post here is the shortest and simplest way I came up with. It works in both Rails 2 and Rails 3 with minor tweaks.
Create an initializer and put the following code inside it. For Rails 3, change RAILS_ROOT to Rails.root.
theme = ActionView::Base.process_view_paths(File.join(RAILS_ROOT, 'theme', "#{SETTINGS["theme"]}", 'views')) ActionController::Base.prepend_view_path(theme)
You’ll also need to set up the SETTINGS constant. I do this by creating the constant in config/environment.rb.
In Rails 3, I have the file look like this.
# Load the rails application require File.expand_path('../application', __FILE__) SETTINGS = YAML.load(Rails.root.join(‘config’, ‘settings.yml’).open) # Initialize the rails application Themetest::Application.initialize!
For Rails 2, I put the SETTINGS line before the boot file require.
You can then create a config/settings.yml file with a theme entry that specifies the name of the theme you want to use.
theme: default
This will prepend the directory RAILS_ROOT/theme/default/views to the view search path. Since it is the first in the path, Rails will search it first and then fall back down through to app/views. This means you can change parts of your application views if you want to and leave the rest to the “main” views.
This still requires that you keep your stylesheets and javascript in the public directory. I just create a theme directory in public/stylesheets and public/javascripts and replicate the root theme directory. It works pretty well for my uses.
I hope you find this helpful. It’s very simple and straightforward.





















FYI, Rails.root is a Pathname object. That means you can do this: YAML.load(Rails.root.join(‘config’, ‘settings.yml’).open).
I’ll adjust to make it simpler. Thank you!
real nice idea – thanks for sharing
[...] Theming in Rails 2 and Rails 3 | Definitive Code (tags: rails theme) [...]
Hi,
Using “prepend_view_path” to support multiple themes is a very expensive solution. You can see another solution to this problem here: http://www.axehomeyg.com/2009/06/10/view-path-m...
-ozgun.
That would be true if the theme variable were a string. It is not.