From 23aa94a7b2d51536baa5eb91a8cd50cdd6dfa99e Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Mon, 2 Dec 2013 16:51:13 +0100 Subject: `mail()` without arguments is a getter for the current mail. This behavior is documented in our guides (http://edgeguides.rubyonrails.org/action_mailer_basics.html#action-mailer-callbacks) but was broken in the past. This commit short curcuits the `mail` method if: 1. mail() was previously called 2. no headers are passed 3. no block is passed Closes #13090. /cc @pixeltrix --- actionmailer/CHANGELOG.md | 19 +++++++++++++++++++ actionmailer/lib/action_mailer/base.rb | 2 ++ actionmailer/test/base_test.rb | 21 +++++++++++++++++++++ 3 files changed, 42 insertions(+) (limited to 'actionmailer') diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index dc8c6bdf74..857cde399a 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -1,3 +1,22 @@ +* Calling `mail()` without arguments serves as getter for the current mail + message and keeps previously set headers. + + Example: + + class MailerWithCallback < ActionMailer::Base + after_action :a_callback + + def welcome + mail subject: "subject", to: ["joe@example.com"] + end + + def a_callback + mail # => returns the current mail message + end + end + + *Yves Senn* + * Instrument the generation of Action Mailer messages. The time it takes to generate a message is written to the log. diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 501fee55aa..6f8ae05539 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -689,6 +689,8 @@ module ActionMailer # end # def mail(headers = {}, &block) + return @_message if @_mail_was_called && headers.blank? && !block + @_mail_was_called = true m = @_message diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb index b74728ae34..c1759d9b92 100644 --- a/actionmailer/test/base_test.rb +++ b/actionmailer/test/base_test.rb @@ -671,6 +671,27 @@ class BaseTest < ActiveSupport::TestCase assert_equal ["robert.pankowecki@gmail.com"], DefaultFromMailer.welcome.from end + test "mail() without arguments serves as getter for the current mail message" do + class MailerWithCallback < ActionMailer::Base + after_action :a_callback + + def welcome + headers('X-Special-Header' => 'special indeed!') + mail subject: "subject", body: "hello world", to: ["joe@example.com"] + end + + def a_callback + mail.to << "jane@example.com" + end + end + + mail = MailerWithCallback.welcome + assert_equal "subject", mail.subject + assert_equal ["joe@example.com", "jane@example.com"], mail.to + assert_equal "hello world", mail.body.encoded.strip + assert_equal "special indeed!", mail["X-Special-Header"].to_s + end + protected # Execute the block setting the given values and restoring old values after -- cgit v1.2.3