Sha256: 56668de3a6935f978e3b1926f1c797dc7885f0b10b3f7dff6c264d8c2ccf2f91

Contents?: true

Size: 1.64 KB

Versions: 8

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

module RubySmart
  module SimpleLogger
    module Devices
      class MultiDevice

        attr_reader :devices
        attr_reader :status

        def self.register(*args)
          new.register(*args)
        end

        def initialize
          @devices = []
          @status  = true
        end

        # pass data to the devices
        # @param [Object] data
        def write(data)
          return false unless status

          devices.each do |device|
            if device[:formatter]
              device[:dev].write(device[:formatter].(*data))
            else
              device[:dev].write(data)
            end
          end
        end

        alias_method :<<, :write

        # disables writing
        def close
          @status = false
        end

        # enables writing
        def reopen
          @status = true
        end

        # clears all devices
        def clear!
          @devices = []
        end

        # registers a new device.
        # CHAINABLE
        #
        # @param [Object] dev
        def register(dev, formatter = nil)
          # check device, to prevent nested sets of +MultiDevice+
          if dev.is_a?(MultiDevice)
            @devices += dev.devices
          else
            @devices << {
              dev:       dev,
              formatter: formatter
            }
          end

          self
        end

        # returns logs from the first loggable device
        # @return [Array] logs
        def logs
          logdev = devices.detect { |device| device[:dev].respond_to?(:logs) }
          logdev.nil? ? [] : logdev[:dev].logs
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
ruby_smart-simple_logger-1.5.3 lib/ruby_smart/simple_logger/devices/multi_device.rb
ruby_smart-simple_logger-1.5.2 lib/ruby_smart/simple_logger/devices/multi_device.rb
ruby_smart-simple_logger-1.5.1 lib/ruby_smart/simple_logger/devices/multi_device.rb
ruby_smart-simple_logger-1.5.0 lib/ruby_smart/simple_logger/devices/multi_device.rb
ruby_smart-simple_logger-1.4.0 lib/ruby_smart/simple_logger/devices/multi_device.rb
ruby_smart-simple_logger-1.3.0 lib/ruby_smart/simple_logger/devices/multi_device.rb
ruby_smart-simple_logger-1.2.2 lib/ruby_smart/simple_logger/devices/multi_device.rb
ruby_smart-simple_logger-1.2.1 lib/ruby_smart/simple_logger/devices/multi_device.rb