For CSS, I use this little helper:
Code:
def stylesheet_include_tag(*sources)
if sources.include?(:controller)
sources.delete(:controller)
sources.push(controller_stylesheet_source) if stylesheet_exists(controller_stylesheet_source)
end
if sources.include?(:action)
sources.delete(:action)
sources.push(action_stylesheet_source) if stylesheet_exists(action_stylesheet_source)
end
if sources.include?(:defaults)
sources.delete(:defaults)
sources.unshift('application')
sources.push(controller_stylesheet_source) if stylesheet_exists(controller_stylesheet_source)
sources.push(action_stylesheet_source) if stylesheet_exists(action_stylesheet_source)
end
sources.collect { |source|
path = "/stylesheets/#{source}.css"
tag('link', { 'type' => 'text/css', 'rel' => 'stylesheet', 'href' => path})
}.join("\n")
end
protected
def controller_stylesheet_source
params[:controller]
end
def action_stylesheet_source
[params[:controller], params[:action]].join("_")
end
def stylesheet_path(source)
"#{RAILS_ROOT}/public/stylesheets/#{source}.css"
end
def stylesheet_exists(source)
File.exists?(stylesheet_path(source))
end
You can put the above in your ApplicationHelper or a separate file and include it in your ApplicationHelper.
You can now use stylesheet_include_tag in your layout - it takes three options; :controller, :action and :defaults.
If you add :controller, it will look for /public/stylesheets/controllername.css and if it finds one it will automatically include it.
If you add :action, it will look for /public/stylesheets/controllername_actionname.css and if it finds one it will automatically include it.
Finally, there is :defaults will look for both controller and action stylesheets, as well as a stylesheet called application.css.
By using the above helper you don't need to worry about specifying stylesheets - just create one using the above naming schemes and it will be included.
Bookmarks