Dynamic template system with RoR

For this site, we will be accepting clients with their own domain name. All of these domain names will be pointed to the same directory on our

server, where the client application lives. I need to be able to use all the same logic – the controllers, right? – but load a different template for each domain, so that each looks like its own site. I have

already determined how to get the domain name being accessed, and can look up which theme the site is using in my database. My confusion comes in what to do next, and how to organize this.

In PHP, I would have a /themes/ directory with a bunch of different

subdirectories, each containing a set of templates. When the client’s site first loads, I would do a query to find out which theme path they are supposed to be using. Let’s say it’s /themes/silver. I would set

that as a session variable and use it whenever loading a template file. How should I approach this in RoR?

My initial thought is using layouts:

You can define the layout for a controller as a function, meaning you could do something like this

def MyController < ApplicationController layout :themed_layout

def themed_layout session[:layout] ||= Layout.find_by_domain() end end

What the above code does is call the themed_layout function whenever someone accesses an action in MyController. The function will use some code to find out which layout should be used (Here, I’m doing it via a call to a lookup table in an imaginary DB), and cache that into the session[:layout] variable… meaning that the first time it is called, it pulls from the DB, and thereafter, it will simply use what’s stored in session[:layout]. If the session is somehow invalidated, it will re-make the DB call and restore it in the session.

Is this kind of what you’re looking for?

Matt, I'm going to be trying to do exactly what you describe in your post. I'm going to try to build one domain CMS type website that handles many different domains and changes not only the data but also the HTML code on each site that comes from a database record. Would it be ok if I asked you a few questions along the way? David dak AT itracker DOT com

You really need to read AWDWR (Agile Web Development With Rails… you can find it here: http://www.pragmaticprogrammer.com/titles/rails)..)… it’s great, it teaches you how to do most everything you want to do with Rails, and will give you a good framework to build on to find the things it doesn’t teach… basically, it seems like what you need is a mixture of layouts, partials, and the ability to use File.exist? wisely… I would definitely read that book, and quite probably also read Programming Ruby (http://pragmaticprogrammer.com/titles/ruby/index.html ) for a good intro to the language Rails was written with, and that you will be using to customize your Rails app to fit your needs.