Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a before_filter in UserMailer which checks if it is OK to mail a user?

is there a global way I can write a before_filter for my user mailer, that checks to see if the user has emails disabled? Right now every mailer I have checks the user's setting, this is very redundant. I would like to DRY this up by having a before_filter that works for all mailers.

class UserMailer < ActionMailer::Base   before_filter :check_if_we_can_mail_the_user   ....   private     def check_if_we_can_mail_the_user      if current_user.mail_me == true        #continue      else       Do something to stop the controller from continuing to mail out      end    end  end 

Possible? Has anyone done something like this? Thanks

like image 279
AnApprentice Avatar asked Dec 21 '11 18:12

AnApprentice


1 Answers

Rails 4 already has before_filter and after_filter callbacks. For Rails 3 users, it's surprisingly simple to add them: just include AbstractController::Callbacks. This mimics the change to Rails 4 which apart from comments and tests, just included Callbacks.

class MyMailer < ActionMailer::Base   include AbstractController::Callbacks    after_filter :check_email    def some_mail_action(user)     @user = user     ...   end    private   def check_email     if @user.email.nil?       mail.perform_deliveries = false     end     true   end  end 
like image 124
naudster Avatar answered Oct 02 '22 12:10

naudster