【问题标题】:Devise reconfirmation hook设计再确认挂钩
【发布时间】:2018-06-06 14:37:18
【问题描述】:

这个问题与Rails Devise: after_confirmation 非常相似,只是我正在寻找更具体的重新确认挂钩

我的用例:我需要在某个第三方服务(确切地说是对讲)上同步新用户电子邮件。

我有一个使用 API 的第一个实现,我在那里放置了我需要的逻辑(全部整理在一个服务中)

但是,我经常使用控制台进行大量维护,最明显的事情就是执行

user.email = 'newemail@example.com'
user.confirm # or skip_reconfirmation
user.save

使用它,我不会自动触发我的重新同步逻辑。有没有办法强制进行一些重新确认回调?覆盖 after_confirmation 似乎不起作用

【问题讨论】:

    标签: ruby-on-rails devise ruby-on-rails-5 devise-confirmable


    【解决方案1】:

    不是一个真正的答案,但与此同时,我已经使用以下内容对我的用户类进行了猴子补丁(其中xxx 表示在用户类中添加的一些自定义方法,以将新电子邮件同步到第三方服务)

    class User
      include User::Console if defined?('Rails::Console')
    end
    
    module User::Console
      extend ActiveSupport::Concern
    
      included do
        ## Override Devise confirmable to add warnings
    
        def confirmation_warning
          puts "WARNING !!".red
          puts "calling `#confirm` or `#skip_reconfirmation!` on the user does not sync to xxx !\n"\
            'Please either use [Name of custom confirmation service], '\
            'or use `user.sync_to_xxx` to propagate changes'.red
        end
    
        def confirm
          confirmation_warning
          super
        end
    
        def skip_reconfirmation!
          confirmation_warning
          super
        end
      end
    end
    

    【讨论】:

      【解决方案2】:

      我有完全相同的用例,我需要在第三方服务上同步新用户电子邮件。

      我解决它的方法是在User 模型上使用before_update 过滤器,并使用email_changed?

      class User < ApplicationRecord    
      
        before_update :update_email_in_third_party_service
      
        private
      
        def update_email_in_third_party_service
          return unless self.valid? && self.email_changed?
      
          # We passed our check, update email in the third party service (preferably in a background job)
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-24
        • 1970-01-01
        • 1970-01-01
        • 2021-03-16
        相关资源
        最近更新 更多