forked from dbalatero/monster_mash
/
request.rb
101 lines (84 loc) · 2.28 KB
/
request.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
99
100
101
module MonsterMash
class InvalidRequest < StandardError; end
class Request
attr_accessor :options
attr_accessor :errors
attr_accessor :caller_klass
# Creates a new Request wrapper object.
#
# @param [Symbol] type of HTTP request - :get, :post, :delete, :put
def initialize(http_method, *args, &block)
@handler = nil
@value = nil
self.options = { :method => http_method }
execute_dsl(*args, &block)
end
def method_missing(method, *args, &block)
if caller_klass && caller_klass.respond_to?(method)
caller_klass.send(method, *args, &block)
else
super
end
end
def respond_to?(method)
(caller_klass && caller_klass.respond_to?(method)) || super
end
def apply_defaults(default_blocks)
default_blocks.each { |block| execute_dsl(&block) }
end
def execute_dsl(*args, &block)
instance_exec(*args, &block) if block_given?
end
def build_request
Typhoeus::Request.new(self.uri, self.options)
end
def run_serial_request
Typhoeus::Request.run(self.uri, self.options)
end
def valid?
self.errors = []
if !handler
self.errors << 'You need to set a handler block.'
end
if !uri
self.errors << 'You need to set a uri.'
end
self.errors.empty?
end
def uri(value = nil)
if value
@uri = value
end
@uri
end
def handler(&block)
if block_given?
@handler = block
end
@handler
end
# Typhoeus options.
[:body, :headers, :timeout, :cache_timeout, :params,
:user_agent, :follow_location, :max_redirects,
:proxy, :disable_ssl_peer_verification].each do |method|
class_eval <<-EOF
def #{method}(value = nil, &block)
assign_or_return_option!(:#{method}, value, &block)
end
EOF
end
private
def assign_or_return_option!(name, value = nil)
symbolized_name = name.to_sym
if value
if self.options[symbolized_name].respond_to?(:merge) and value.respond_to?(:merge)
self.options[symbolized_name].merge!(value)
else
self.options[symbolized_name] = value
end
else
self.options[symbolized_name]
end
end
end
end