/
link.rb
89 lines (73 loc) · 1.99 KB
/
link.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
module Webrat
class Link
def initialize(page, element)
@page = page
@element = element
end
def click(method = nil, options = {})
method ||= http_method
return if href =~ /^#/ && method == :get
options[:javascript] = true if options[:javascript].nil?
if options[:javascript]
Page.new(@page.session, absolute_href, method, data)
else
Page.new(@page.session, absolute_href, :get, {})
end
end
def matches_text?(link_text)
text =~ /#{Regexp.escape(link_text.to_s)}/i
end
def text
@element.innerHTML
end
protected
def data
authenticity_token.blank? ? {} : {"authenticity_token" => authenticity_token}
end
def href
@element["href"]
end
def absolute_href
if href =~ %r{^https?://www.example.com(/.*)}
$LAST_MATCH_INFO.captures.first
elsif href =~ /^\?/
"#{@page.url}#{href}"
elsif href !~ /^\//
"#{@page.url}/#{href}"
else
href
end
end
def authenticity_token
return unless onclick && onclick.include?("s.setAttribute('name', 'authenticity_token');") &&
onclick =~ /s\.setAttribute\('value', '([a-f0-9]{40})'\);/
$LAST_MATCH_INFO.captures.first
end
def onclick
@element["onclick"]
end
def http_method
if !onclick.blank? && onclick.include?("f.submit()")
http_method_from_js_form
else
:get
end
end
def http_method_from_js_form
if onclick.include?("m.setAttribute('name', '_method')")
http_method_from_fake_method_param
else
:post
end
end
def http_method_from_fake_method_param
if onclick.include?("m.setAttribute('value', 'delete')")
:delete
elsif onclick.include?("m.setAttribute('value', 'put')")
:put
else
raise "No HTTP method for _method param in #{onclick.inspect}"
end
end
end
end