/
double_web.rb
98 lines (81 loc) · 1.97 KB
/
double_web.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
module DoubleWeb
module DriverPatches
autoload :NetHTTP, 'double_web/driver_patches/net_http'
end
module Caches
autoload :Base, 'double_web/caches/base'
autoload :Memory, 'double_web/caches/memory'
autoload :Yaml, 'double_web/caches/yaml'
end
class UnexpectedRequestError < StandardError; end
def self.init!
case ENV['internet']
when 'on' then puts "DoubleWeb: inactive"; clear!
when 'off' then puts "DoubleWeb: playback mode"; playback!
when 'watch' then puts "DoubleWeb: watching"; watch!
else
puts "DoubleWeb: set the `internet` enviroment variable to control DoubleWeb",
" options are 'on', 'off', 'watch'",
" DoubleWeb is currently disabled."
end
end
def self.patch!
unless @patched
require 'net/http' unless defined?(Net::HTTP)
Net::HTTP.send(:include, DoubleWeb::DriverPatches::NetHTTP)
Net::HTTPRequest.send(:include, DoubleWeb::DriverPatches::NetHTTP::RequestPatch)
Net::HTTPResponse.send(:include, DoubleWeb::DriverPatches::NetHTTP::ResponsePatch)
end
@patched = true
end
def self.watch!
patch!
@watch = true
if block_given?
res = yield
@watch = false
res
end
end
def self.unwatch!
@watch = false
end
def self.watch?
@watch
end
def self.playback!
patch!
@playback = true
if block_given?
res = yield
@playback = false
res
end
end
def self.stop_playback!
@playback = false
end
def self.playback?
@playback
end
def self.clear!
unwatch!
stop_playback!
cache.clear
end
def self.cache_strategy=(strategy)
@cache_strategy = {
:memory => DoubleWeb::Caches::Memory,
:yaml => DoubleWeb::Caches::Yaml
}[strategy]
end
def self.cache
(@cache_strategy ||= DoubleWeb::Caches::Memory).cache
end
def self.[](request)
cache[request]
end
def self.[]=(request, response)
cache[request] = response
end
end