Rails Observer Alternatives for 4.0

前端 未结 12 799
伪装坚强ぢ
伪装坚强ぢ 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:37

    How about using a PORO instead?

    The logic behind this is that your 'extra actions on save' are likely going to be business logic. This I like to keep separate from both AR models (which should be as simple as possible) and controllers (which are bothersome to test properly)

    class LoggedUpdater
    
      def self.save!(record)
        record.save!
        #log the change here
      end
    
    end
    

    And simply call it as such:

    LoggedUpdater.save!(user)
    

    You could even expand on it, by injecting extra post-save action objects

    LoggedUpdater.save(user, [EmailLogger.new, MongoLogger.new])
    

    And to give an example of the 'extras'. You might want to spiffy them up a bit though:

    class EmailLogger
      def call(msg)
        #send email with msg
      end
    end
    

    If you like this approach, I recommend a read of Bryan Helmkamps 7 Patterns blog post.

    EDIT: I should also mention that the above solution allows for adding transaction logic as well when needed. E.g. with ActiveRecord and a supported database:

    class LoggedUpdater
    
      def self.save!([records])
        ActiveRecord::Base.transaction do
          records.each(&:save!)
          #log the changes here
        end
      end
    
    end
    

提交回复
热议问题