문제

I have a simple function to prevent emails from being sent to customers when testing locally:

def safe_emails emails
  if Rails.env == 'production'
    emails
  else
    emails.select{|e| ['staff@example.com', 'staff2@example.com'].include?(e) }
  end
end

I want to share that function between mailers. I can see two options, a module or a class method.

Option 1: Module

class ReportMailer < ActionMailer::Base
  include SafeEmailer

  def daily emails
    mail_to: safe_emails(emails)
  end
end

Option2: Class Method

class ReportMailer < ActionMailer::Base
  def daily emails
    mail_to: SafeEmailer.safe_emails(emails)
  end
end

The class method is a no-no according to some due to global scope, including a module with one method doesnt seem all that attractive. Monkey-patching ActionMailer to throw the method in there also seems like it could cause trouble (when Rails 4.3 introduces the safe_emails method or whatever).

도움이 되었습니까?

해결책

I would go with module option even if it's a simple one function module. Keeping a generic function that can eventually be used by multiple classes in a module makes much more sense than defining it inside a class.

If Rails 4.3 is of your concern then you can simply replace your include MySafeEmailModule with whatever Rails 4.3 would include this function in, as compared to find and replace all calls to ReportMailer.daily_emails.

다른 팁

Neither – in your case, you'd need a policy object, that decides who receives email regarding the Rails.env. I'd keep that logic outside the ReportMailer.

I'd go with something like:

UserMailer.welcome_email(@user).deliver if SafeEmailer.new(@user.email).safe?

This is probably the easiest way.

Set the below configuration in your non production environments.(config/environments/.rb)

config.action_mailer.delivery_method = :smtp (default), :sendmail, :test, or :file

Have a look at letter opener gem. You could have the delivery_method set as letter_opener and have the emails open in browser instead of actually sending them in your non production environments.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top