Sha256: 1bcf5b08abf14bbec4519dfdff9f10a30a4d39c8a045ed534f9ee16ce876d44a

Contents?: true

Size: 1.83 KB

Versions: 6

Compression:

Stored size: 1.83 KB

Contents

require_relative 'observer'
require 'fileutils'
require 'logger'

module StateInspector
  module Observers
    module SessionLoggerObserver
      class << self
        include Observer
        def update *values
          folder = File.join ['log', 'state_inspector']
          @file ||= File.join(
              folder,
              ['session', Time.now.to_i, 'log'].join('.')
            )
          FileUtils.mkdir_p folder
          File.open(@file, File::WRONLY | File::APPEND | File::CREAT) do |file|
            logger = Logger.new(file)
            logger << values.
              map(&value_mapper).
              join(splitter) 
            logger << "\n"
          end
        end

        def file= f
          warn("Warning! Log file #{@file} was already set!") if @file
          @file = f
        end

        def display
          if @file
            File.open(@file, File::RDONLY) {|f| f.read }
          else
            ""
          end
        end

        def values
          if @file
            File.open(@file, File::RDONLY) {|f| f.readlines}.map(&:chomp).map do |line|
              if line.empty?
                nil
              else
                line.split(splitter).map(&value_mapper)
              end
            end.compact
          else
            []
          end
        end

        def purge
          File.delete(@file) if File.exist? @file
          @file = nil
        end

        private
        def splitter
          "\t\t"
        end

        def value_mapper
          ->v{
            case v
            when nil
              "nil"
            when "nil"
              nil
            when Symbol
              v.inspect
            when ->val{ val.is_a?(String) && val =~ /\A:/ }
              v[1..-1].to_sym
            else
              v
            end
          }
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
state_inspector-1.0.1 lib/state_inspector/observers/session_logger_observer.rb
state_inspector-1.0.0 lib/state_inspector/observers/session_logger_observer.rb
state_inspector-1.0.0.rc1 lib/state_inspector/observers/session_logger_observer.rb
state_inspector-0.8.2 lib/state_inspector/observers/session_logger_observer.rb
state_inspector-0.8.1 lib/state_inspector/observers/session_logger_observer.rb
state_inspector-0.8.0 lib/state_inspector/observers/session_logger_observer.rb