Sha256: b9b68cf714942ce6be5717f176d5e83f172c71ec95a8cacc9f415892a64568b6

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

module ActiveRecordMigrationUi
  #
  # This logger is used to disable temporarily the ActionCable logger before
  # broadcasting a message avoiding an infinit loop as ActiveCable wants to log
  # that it is broadcasting.
  #
  class MutedLogger < StringIO
    def debug(*); end

    def info(*); end
  end

  #
  # Captures the Rails.logger logs, looking for the one from ActiveRecord::Base
  # and broadcast them to the front app through ActionCable.
  #
  # This allows this gem to show the migration output in real-time.
  #
  class Logger < StringIO
    def add(_, message = nil, progname = nil)
      final_message = message || progname

      return unless ActiveRecordMigrationUi.running_migration?

      # Ignore empty logs
      return unless final_message

      # Avoids infinit loop from ActionCable logging that it is broadcasting.
      return if action_cable_is_speaking_in?(final_message)

      # Replace the actual logger with the MutedLogger
      old_logger = ActionCable.server.config.logger
      ActionCable.server.config.logger = MutedLogger.new

      # Broadcast the message to the front
      ActionCable.server.broadcast ActiveRecordMigrationUi.ac_channel_name,
                                   command: 'log',
                                   message: final_message.gsub(/(\[\d+m)/, '')

      # Revert the logger
      ActionCable.server.config.logger = old_logger
    end

    private

    def action_cable_channel_name
      ActiveRecordMigrationUi.ac_channel_class_name
    end

    def action_cable_is_speaking_in?(message)
      message =~ /^#{action_cable_channel_name}( is)? (transmitting|streaming)/
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_record_migration_ui-0.1.2 lib/active_record_migration_ui/logger.rb