posted on Tuesday, December 14, 2010
There is an easy way to add view path dynamicly inside ActionController using prepend_view_path or append_view_path. But there is a problem because each request will start a filesystem traversal to do a pathset, we don't want to do that especially if there is a big project.
So here is an idea of how to handle that view_path insertion...
application_controller:
class ApplicationController < ActionController::Base
before_filter :set_custom_view
protected
def set_custom_view
custom_slug = CUSTOM_VIEWS.select {|k,v| request.subdomain.match(Regexp.new(k))}.first
prepend_view_path(preprocessed_pathsets[ApplicationController.custom_view_path(custom_slug.last)]) if custom_slug
end
end
somewhere inside config/initializers:
ActionController::Base.class_eval do
CUSTOM_VIEWS = {"custom_project"=>"project1", "another_project"=>"project2"}
def self.custom_view_path name
name=="views" ? "app/views" : "app/views_custom/#{name}"
end
# preprocess some pathsets on boot
# doing pathset generation during a request is very costly
@@preprocessed_pathsets = begin
CUSTOM_VIEWS.values.inject({}) do |pathsets, slug|
path = ActionController::Base.custom_view_path(slug)
pathsets[path] = ActionView::Base.process_view_paths(path).first
pathsets
end
end
cattr_accessor :preprocessed_pathsets
end
Modified version of unspace's code.
comments