Passing parameters to MailView or ActionMailer :: Preview in Ruby on Rails

Is it possible to use MailView gem or Rails 4.1 post previews to pass parameters to MailView? I would like to be able to use query string parameters in the preview urls and access them in the MailView to dynamically select which entry to display in the preview.

+3


source to share


2 answers


I stumbled upon the same issue, and as far as I understand, from reading the Rails code, it is not possible to access the request parameters from the mailer preview.

Slope line 22 in Rails::PreviewsController

(email is the name of the mailer method)



@email = @preview.call(email)

      

+6


source


It is still an actual question and there are still very few solutions that can be found on the Internet (especially elegant ones). I hacked my way through this one today and came up with this solution and blog post about the ActionMailer extension .



# config/initializers/mailer_injection.rb

# This allows `request` to be accessed from ActionMailer Previews
# And @request to be accessed from rendered view templates
# Easy to inject any other variables like current_user here as well

module MailerInjection
  def inject(hash)
    hash.keys.each do |key|
      define_method key.to_sym do
        eval " @#{key} = hash[key] "
      end
    end
  end
end

class ActionMailer::Preview
  extend MailerInjection
end

class ActionMailer::Base
  extend MailerInjection
end

class ActionController::Base
  before_filter :inject_request

  def inject_request
    ActionMailer::Preview.inject({ request: request })
    ActionMailer::Base.inject({ request: request })
  end
end

      

+2


source







All Articles