Per-request Template Paths in Rails Edge (> 1.2.3)
Published 7 June 07 by Justin French
If you’re playing with Rails edge (> 1.2.3) and want to set the template path on a per-request basis, the game has changed a little.
But first, why would you want this? Let’s say you’re building a CMS that has to use a different set of views based on something in the request, like the host name:
app
views
siteone.com
posts
index.html.erb
show.html.erb
...
sitetwo.com
posts
index.html.erb
show.html.erb
...
Courtesy of the ever-helpful Rick Olsen, this is how we used to do it, but recently ActionPack has been changed to support multiple view paths that act like load paths (first look here, then here, then here). It’s a great addition to the framework, and really useful for plugin developers (first look for an overriding view in app/views/, then look in vendor/plugin/myplugin/views/, for example).
But somewhere in the changes “the old way” stopped working, and there’s no “new way” that I can find that works on edge right now, but Courtenay has a proposed fix which is a one-line change in ActionView::Base to change an attr_reader into an attr_accessor, then replace the old way with the new way:
self.class.view_paths = File.expand_path("#{RAILS_ROOT}/themes/#{store.id}/views")
@template.view_paths = File.expand_path("#{RAILS_ROOT}/themes/#{store.id}/views")
I really hope the one-liner (or an officially supported API) makes it into trunk soon, but in the meantime (that’s a great song by Helmet by the way) it’s nice to know the hack isn’t too crazy.
Before you go…
Here’s some links to my most popular posts: