Class: Lijab::HistoryHandler::History

Inherits:
Object
  • Object
show all
Defined in:
lib/lijab/history.rb

Constant Summary collapse

MEMORY_LOG_LENGTH =
50

Instance Method Summary collapse

Constructor Details

#initialize(path, target = nil, log_to_session = false) ⇒ History

Returns a new instance of History.


23
24
25
26
# File 'lib/lijab/history.rb', line 23

def initialize(path, target=nil, log_to_session=false)
   @path, @target, @log_to_session = path, target, log_to_session
   @m = []
end

Instance Method Details

#init_logfileObject


28
29
30
31
32
# File 'lib/lijab/history.rb', line 28

def init_logfile
   @w = File.open(@path, 'a')
   @r = File.open(@path, 'r')
   @r.return_if_eof = true
end

#last(n) ⇒ Object


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/lijab/history.rb', line 55

def last(n)
   return [] if n <= 0

   init_logfile() unless @r

   if n <= @m.length
      @m[-n..-1]
   else
      ret = []
      @r.seek(0, File::SEEK_END)
      @r.backward(n)
      @r.tail(n-@m.length) do |l|
         time, target, direction, msg = l.split(" ", 4)
         ret << {:time => Time.parse(time).localtime,
                 :target => target,
                 :direction => direction == "<-" ? :from : :to,
                 :msg => msg.strip.unpack("M").first}
      end
      ret += @m
      if @m.length < MEMORY_LOG_LENGTH
         @m = (ret[0...n-@m.length] + @m)
         @m = @m[-MEMORY_LOG_LENGTH..-1] if @m.length > MEMORY_LOG_LENGTH
      end
      ret
   end
end

#log(msg, direction, target = nil) ⇒ Object


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/lijab/history.rb', line 34

def log(msg, direction, target=nil)
   init_logfile() unless @w

   time = Time.now.utc
   target ||= @target
   arrow = direction == :from ? "<-" : "->"
   quoted = [msg].pack("M").gsub(/=?\n/) { |m| m[0] == ?= ? "" : "=0A" }

   @w.puts("#{time.iso8601} #{target} #{arrow} #{quoted}")
   @w.flush

   @m.push({:time=>time.localtime, :target=>target, :direction=>direction, :msg=>msg})
   @m.shift if @m.length > MEMORY_LOG_LENGTH

   @m = []

   HistoryHandler::log(msg, direction, target) if @log_to_session

   self
end