Rails Dispatch

Rails news delivered fresh

Presented by Engine Yard

View Question

Vote on questions you’d like to see answered by the expert contributors

Signup to ask questions or vote for the questions you’d like to see answered.

Great screencast on the new action mailer.

One question though.

You used a default to setup a tracking timestamp.

Won’t Time.now only get evaluated when the class is loaded, so every email sent from a run of the server in a mode which doesn’t reload classes use the same timestamp.

Does ActionMailer allow you to pass a proc for default values so that they can be lazy evaluated?

Asked April 29, 2010
Mikel Lindsaar answered
Answer

On the using a default to track the timestamp, you are absolutely right and it was probably a bad example given that.

The proc idea is a great idea, so I just wrote a patch that implements this, it is now in the “Rails Github repository”: and look forward to it in the next rails release or by tracking Rails git in your Gemfile.

I also added the ability to call ActionMailer instance methods as well.

You would call it like so:

class Notifier < ActionMailer::Base
  default :from => "mikel@rubyx.com",
          :reply_to => "enquiries@rubyx.com",
          "X-Time-Code" => Proc.new { Time.now.to_i.to_s },
          "X-Special-Method" => Proc.new { my_method }

  def welcome_email(user)
    @name = user.name
    @message = user.message
    mail(:to => user.email, :subject => "G'day Mate!", 
      :sender => "system@rubyx.com")
  end

  private

  def my_method
    "This is some arbitrary string"
  end

end

The resulting Proc gets called ON generation of the Mail object, not when it is sent.

Thanks for pointing it out!

Answered May 02, 2010