Monkey patching Devise (or any Rails gem)

后端 未结 7 1361
甜味超标
甜味超标 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:58

    Using Rails 4 @aceofspades answer didn't work for me.

    I kept getting require': cannot load such file -- devise/app/controllers/devise_controller (LoadError)

    Instead of screwing around with load order of initializers I used the to_prepare event hook without a require statement. It ensures that the monkey patching happens before the first request. This effect is similar to after_initialize hook, but ensures that monkey patching is reapplied in development mode after a reload (in prod mode the result is identical).

    Rails.application.config.to_prepare do
      DeviseController.class_eval do
        # Your new methods here
      end
    end
    

    N.B. the rails documentation on to_prepare is still incorrect: See this Github issue

提交回复
热议问题