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

前端 未结 4 829
余生分开走
余生分开走 2021-01-17 07:50

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 se

相关标签:
4条回答
  • 2021-01-17 08:11

    I haven't done this, but I've done similar things with an email interceptor.

    class MailInterceptor    
        def self.delivering_email(message)
            if User.where( :email => message.to ).first.mail_me != true
                message.perform_deliveries = false
            end
        end
    end
    

    You won't have access current_user, so you find the user by email, which should already be in the mail object as the 'to' field.

    There's a good Railscast covering setting up email interceptors. http://railscasts.com/episodes/206-action-mailer-in-rails-3?view=asciicast

    0 讨论(0)
  • 2021-01-17 08:11

    Maybe check out https://github.com/kelyar/mailer_callbacks. It looks like it will do what you want.

    0 讨论(0)
  • 2021-01-17 08:12

    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
    
    0 讨论(0)
  • 2021-01-17 08:21

    I edited @naudster 's answer to get the information from message

    class MyMailer < ActionMailer::Base
      include AbstractController::Callbacks
    
      after_filter :check_email
    
      private
      def check_email
        if message.to.nil?
          message.perform_deliveries = false
        end
      end
    
    end
    
    0 讨论(0)
提交回复
热议问题