Skip to content

Passing IDs for async

glebm edited this page Sep 12, 2014 · 2 revisions

When sending emails asynchronously, it is best to pass IDs instead of slow to (de)serialize and possibly stale ActiveRecord::Base instances. However, when generating a preview, you want pass a non-persisted record and not an ID. Resolve the conflict by adding a find_record helper that can do both:

# app/mailers/some_mailer.rb
class SomeMailer
  include MailerFindRecord
  def notify(user_or_id)
    user = find_record User, user_or_id
  end
end

# app/mailers/concerns/find_record.rb
module FindRecord
  protected 
  # @param [Class] klass a class that responds to `#find`
  # @param [Object,Fixnum] record_or_id an instance of klass or id
  # @return if passed a record, that record as is, otherwise find the record by id 
  def find_record(klass, record_or_id)
    # in development klass will not equal the record's class after reloading
    if record_or_id.class.name == klass.name
      record_or_id
    else
      klass.find record_or_id
    end
  end
end

# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  include FindRecord
end
Clone this wiki locally