Sunday, June 15, 2008

Tidy Stylesheets, Take Two

Back in February I wrote about a nifty way to have fine-grained control over styles in Rails.

As I was looking at it again, I realized something: The way it was implemented (and the way I adopted it) violates the separation of concerns principle.

That implementation called for a filter in the ApplicationController base class to scan and collect an array of stylesheet file paths in an instance variable. Then the layout used will pull in stylesheets from the said collection.

With that realization, I came up with an alternate approach that moves the code to collect stylesheets into the ApplicationHelper module.

Now, the concern of styles rest squarely with views, and controllers know nothing of them. A clean separation!

Another subtle difference here is that the original version collected the stylesheets whether they are pulled in by the layout or not. The new implementation will collect stylesheets only if the layout decides to use them.

The relevant code snippets are as follows:

  def get_stylesheets
stylesheets = [] unless stylesheets
"#{controller.controller_path}/#{controller.action_name}"].each do |ss|
stylesheets << ss if File.exists? "#{Dir.pwd}/public/stylesheets/#{ss}.css"
  <%= stylesheet_link_tag(*get_stylesheets) %>

1 comment:

Unknown said...

How do you modify this to give absolute URL's for the stylesheets?