Rails Observer Alternatives for 4.0

前端 未结 12 798
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 05:29

With Observers officially removed from Rails 4.0, I\'m curious what other developers are using in their place. (Other than using the extracted gem.) While Observers were cer

12条回答
  •  再見小時候
    2020-12-04 05:30

    Wisper is a great solution. My personal preference for callbacks is that they're fired by the models but the events are only listened to when a request comes in i.e. I don't want callbacks fired while I'm setting up models in tests etc. but I do want them fired whenever controllers are involved. This is really easy to setup with Wisper because you can tell it to only listen to events inside a block.

    class ApplicationController < ActionController::Base
      around_filter :register_event_listeners
    
      def register_event_listeners(&around_listener_block)
        Wisper.with_listeners(UserListener.new) do
          around_listener_block.call
        end
      end        
    end
    
    class User
      include Wisper::Publisher
      after_create{ |user| publish(:user_registered, user) }
    end
    
    class UserListener
      def user_registered(user)
        Analytics.track("user:registered", user.analytics)
      end
    end
    

提交回复
热议问题