2012-10-11 182 views
6

我試圖重寫方法 'send_confirmation_instructions' 如下所示:設計,如何覆蓋send_confirmation_instructions

http://trackingrails.com/posts/devise-send-confirmation-mail-manually-or-delay-them

有:

def send_confirmation_instructions 
    generate_confirmation_token! if self.confirmation_token.nil? 
    ::Devise.mailer.delay.confirmation_instructions(self) 
end 

這似乎不再與合作最新版本的設計。設計文檔顯示如何覆蓋控制器而不是模型。有關如何覆蓋設計模型的任何建議?謝謝

回答

7

當您設置Devise時,您告訴它它正在處理哪個模型(例如用戶);許多/大部分方法適用於該類。所以這就是你想要重寫內容的地方。

這是來自lib/devise/models/authenticatable.rb的設計代碼的評論,它描述瞭如果我正確閱讀,幾乎到底要做什麼。

# This is an internal method called every time Devise needs 
    # to send a notification/mail. This can be overriden if you 
    # need to customize the e-mail delivery logic. For instance, 
    # if you are using a queue to deliver e-mails (delayed job, 
    # sidekiq, resque, etc), you must add the delivery to the queue 
    # just after the transaction was committed. To achieve this, 
    # you can override send_devise_notification to store the 
    # deliveries until the after_commit callback is triggered: 
    # 
    #  class User 
    #  devise :database_authenticatable, :confirmable 
    # 
    #  after_commit :send_pending_notifications 
    # 
    #  protected 
    # 
    #  def send_devise_notification(notification) 
    #   pending_notifications << notification 
    #  end 
    # 
    #  def send_pending_notifications 
    #   pending_notifications.each do |n| 
    #   devise_mailer.send(n, self).deliver 
    #   end 
    #  end 
    # 
    #  def pending_notifications 
    #   @pending_notifications ||= [] 
    #  end 
    #  end 
    # 
    def send_devise_notification(notification) 
    devise_mailer.send(notification, self).deliver 
    end 
+0

謝謝你所以你說要添加「send_devise_notification」到我的user.rb文件?我試過了,它沒有被調用... – AnApprentice

+0

是的,請覆蓋User模型中的'send_devise_notification'。我能夠用當前版本的Devise攔截通知(我剛剛發送了一些警告來證明它可行)。但要使所有的工作都能正常工作,請閱讀註釋 - 這不僅僅是定義方法的問題,您還必須添加'after_commit'過濾器來構建延遲的作業(或其他)隊列。 –

+0

謝謝,但這不是「send_confirmation_instructions」所在的地方嗎?我需要修改該方法「send_confirmation_instructions」 – AnApprentice

0

爲什麼不使用devise-async

Usage 

Devise >= 2.1.1 

Include Devise::Async::Model to your Devise model 

class User < ActiveRecord::Base 
    devise :database_authenticatable, :confirmable # etc ... 

    include Devise::Async::Model # should be below call to `devise` 
end 

Devise < 2.1.1 

Set Devise::Async::Proxy as Devise's mailer in config/initializers/devise.rb: 

# Configure the class responsible to send e-mails. 
config.mailer = "Devise::Async::Proxy" 

All 

Set your queuing backend by creating config/initializers/devise_async.rb: 

# Supported options: :resque, :sidekiq, :delayed_job 
Devise::Async.backend = :resque 
+0

因爲devise-async不存儲您在用戶上設置的虛擬屬性(attr_accessor)。 – AnApprentice

+0

如果你想使用最新版本的設計,這不再是一個選項,你可以在[他們的文檔](https://github.com/mhfs/devise-async#devise--40)中看到他們不支持設計> = 4.0 –