Fellow Stranger
Fellow Stranger

Reputation: 34023

How would I access url parameters in Mailer Preview

I have the following working Preview class:

class UserMailerPreview < ActionMailer::Preview
  def invite
    USerMailer.invite
  end
end

I'm trying to pass paramaters to the method like so:

localhost:3000/rails/mailers/user_mailer/invite?key1=some_value

The server seems to receive them:

Parameters: {"key1"=>"some_value", "path"=>"user_mailer/invite"}

But when trying to access them with the hash params, I get an error.

Can I access these parameters in a Preview method and if so - how?

Upvotes: 5

Views: 1436

Answers (2)

Clay McIlrath
Clay McIlrath

Reputation: 612

I hacked my way through this one today and came up with this solution and blog post on extending ActionMailer.

# 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

Upvotes: 2

Craig Walker
Craig Walker

Reputation: 51727

I dug into the code behind the mailer preview system and discovered that, unfortunately, none of the request parameters are passed to the preview class, and are thus inaccessible to the preview.

The relevant controller action is in railties: Rails::MailersControlller#preview. Here, you can see it calling ActionMailer::Preview#call and just passing the name of the "email" (ie: the appropriate method in the preview).

Upvotes: 3

Related Questions