Class: CarbonCopy::RequestCacher

Inherits:
Object
  • Object
show all
Defined in:
lib/carbon-copy/request_cacher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_dir) ⇒ RequestCacher

Returns a new instance of RequestCacher.



8
9
10
# File 'lib/carbon-copy/request_cacher.rb', line 8

def initialize(base_dir)
  @base_dir = base_dir
end

Instance Attribute Details

#base_dirObject (readonly)

Returns the value of attribute base_dir.



6
7
8
# File 'lib/carbon-copy/request_cacher.rb', line 6

def base_dir
  @base_dir
end

Instance Method Details

#cache_dirObject

Setup cache directory



13
14
15
# File 'lib/carbon-copy/request_cacher.rb', line 13

def cache_dir
  "#{@base_dir}/.request_cache"
end

#connect(request) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/carbon-copy/request_cacher.rb', line 70

def connect(request)
  verify_cached_dir(request)
  cached_path = path(request)

  if File.exist?(cached_path) && !File.zero?(cached_path)
    puts "Getting file #{cached_path} from cache"
    IO.read(cached_path)
  else
    resp = get_response(request)
    File.open(cached_path, "w") do |f|
      f.puts resp
    end
    resp
  end
end

#get_response(request) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/carbon-copy/request_cacher.rb', line 38

def get_response(request)
  a = TCPSocket.new(request.host, request.port)
  a.write(request.request)

  # Pull request data
  content_len = nil
  buff = ""
  loop do
    line = a.readline
    buff += line
    if line =~ /^Content-Length:\s+(\d+)\s*$/
      content_len = $1.to_i
    end
    break if line.strip.empty?
  end

  # Pull response
  if content_len
    buff += a.read(content_len)
  else
    loop do
      if a.eof? || line = a.readline || line.strip.empty?
        break
      end
      buff += line
    end
  end
  a.close

  buff
end

#path(request) ⇒ Object

Determine final path



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/carbon-copy/request_cacher.rb', line 18

def path(request)
  uri = request.uri == "/" ? "" : request.uri.tr("\/", "_")
  hash = Digest::MD5.new << request.header_str
  # Cache directory structure
  """
    #{cache_dir}/
      #{request.host}/
        #{request.verb.downcase}
        #{uri}_
        #{hash}
  """.gsub(/\n|\s/, "")
end

#verify_cached_dir(request) ⇒ Object

Ensure cached directories are created



32
33
34
35
36
# File 'lib/carbon-copy/request_cacher.rb', line 32

def verify_cached_dir(request)
  FileUtils.mkdir_p(cache_dir) unless File.exist?(cache_dir)
  host_cache = "#{cache_dir}/#{request.host}"
  FileUtils.mkdir_p(host_cache) unless File.exist?(host_cache)
end