Monkey patching Devise (or any Rails gem)

后端 未结 7 1367
甜味超标
甜味超标 2020-12-07 23:11

I\'m using the Devise authentication gem in my Rails project, and I want to change the keys it\'s using in flash alerts. (Devise uses :notice and :alert flash keys, but I wa

7条回答
  •  既然无缘
    2020-12-07 23:55

    In your initializer file :

    module DeviseControllerFlashMessage
      # This method is called when this mixin is included
      def self.included klass
        # klass here is our DeviseController
    
        klass.class_eval do
          remove_method :set_flash_message
        end
      end
    
      protected 
      def set_flash_message(key, kind, options = {})
        if key == 'alert'
          key = 'error'
        elsif key == 'notice'
          key = 'success'
        end
        message = find_message(kind, options)
        flash[key] = message if message.present?
      end
    end
    
    DeviseController.send(:include, DeviseControllerFlashMessage)
    

    This is pretty brutal but will do what you want. The mixin will delete the previous set_flash_message method forcing the subclasses to fall back to the mixin method.

    Edit: self.included is called when the mixin is included in a class. The klass parameter is the Class to which the mixin has been included. In this case, klass is DeviseController, and we call remove_method on it.

提交回复
热议问题