Class: ScoutRailsProxy::LayawayFile

Inherits:
Object
  • Object
show all
Defined in:
lib/scout_rails_proxy/layaway_file.rb

Overview

Logic for the serialized file access

Instance Method Summary collapse

Instance Method Details

#dump(object) ⇒ Object



7
8
9
# File 'lib/scout_rails_proxy/layaway_file.rb', line 7

def dump(object)
  Marshal.dump(object)
end

#get_data(f) ⇒ Object



42
43
44
45
46
47
# File 'lib/scout_rails_proxy/layaway_file.rb', line 42

def get_data(f)
  data = read_until_end(f)
  result = load(data)
  f.truncate(0)
  result
end

#load(dump) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/scout_rails_proxy/layaway_file.rb', line 11

def load(dump)
  if dump.size == 0
    ScoutRailsProxy::Agent.instance.logger.debug("No data in layaway file.")
    return nil
  end
  Marshal.load(dump)
rescue ArgumentError, TypeError => e
  ScoutRailsProxy::Agent.instance.logger.debug("Error loading data from layaway file: #{e.inspect}")
  ScoutRailsProxy::Agent.instance.logger.debug(e.backtrace.inspect)
  nil
end

#pathObject



3
4
5
# File 'lib/scout_rails_proxy/layaway_file.rb', line 3

def path
  "#{ScoutRailsProxy::Agent.instance.log_path}/scout_rails_proxy.db"
end

#read_and_writeObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/scout_rails_proxy/layaway_file.rb', line 23

def read_and_write
  File.open(path, File::RDWR | File::CREAT) do |f|
    f.flock(File::LOCK_EX)
    begin
      result = (yield get_data(f))
      f.rewind
      f.truncate(0)
      if result
        write(f, dump(result))
      end
    ensure
      f.flock(File::LOCK_UN)
    end
  end
rescue Errno::ENOENT, Exception  => e
  ScoutRailsProxy::Agent.instance.logger.error(e.message)
  ScoutRailsProxy::Agent.instance.logger.debug(e.backtrace.split("\n"))
end

#read_until_end(f) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/scout_rails_proxy/layaway_file.rb', line 59

def read_until_end(f)
  contents = ""
  while true
    contents << f.read_nonblock(10_000)
  end
rescue Errno::EAGAIN, Errno::EINTR
  IO.select([f])
  retry
rescue EOFError
  contents
end

#write(f, string) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/scout_rails_proxy/layaway_file.rb', line 49

def write(f, string)
  result = 0
  while (result < string.length)
    result += f.write_nonblock(string)
  end
rescue Errno::EAGAIN, Errno::EINTR
  IO.select(nil, [f])
  retry
end