Fork me on GitHub

ActionMailer: Hacking multiple template paths

I was up against a little wall this afternoon and I had to monkey patch my way out.

It struck me as weird that with ActionView you can have a whole array (really Array) of view/template paths that are iteratively searched for a matching template, however, with ActionMailer (even though it uses ActionView) you can only define or override the single template_root.

Bizarre, right? I bet rails core had some good reason for this, but in this specific project I'm relying heavily on using ActionView::Base.prepend_view_path() to have the app structured with default templates that are easily replaced by dropping templates in to a different view path. So if I'm doing that for an entire site it would make sense to do the same for my 'Notification' templates as well. The rails docs were pretty unhelpful, but a quick dive into the source proved fruitful. If you drop the code below into config/initializers/action_mailer_extensions.rb:

module ActionMailer
  class Base
    class_inheritable_accessor :view_paths
    
    def self.prepend_view_path(path)
      view_paths.unshift(*path)
      ActionView::TemplateFinder.process_view_paths(path)
    end

    def self.append_view_path(path)
      view_paths.push(*path)
      ActionView::TemplateFinder.process_view_paths(path)
    end

    private
    def self.view_paths
      @@view_paths ||= [template_root]
    end
    
    def view_paths
      self.class.view_paths
    end
    
    def initialize_template_class(assigns)
      ActionView::Base.new(view_paths, assigns, self)
    end

  end
end
You can do:
ActionMailer::Base.prepend_view_path('/my/other/path/to/search/first/')
# or
ActionMailer::Base.append_view_path('/my/other/path/to/search/last/')

One Response to “ActionMailer: Hacking multiple template paths”

QuirkeyBlog » Blog Archive » ActionMailer: Changing the subject in the template Says:

[...] « ActionMailer: Hacking multiple template paths [...]

Leave a Reply

About

QuirkeyBlog is Aaron Quint's perspective on the ongoing adventure of Code, Life, Work and the Web.

For more information check Quirkey.com

QuirkeyBlog is proudly powered by WordPress

Categories