-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource.rb
46 lines (40 loc) · 929 Bytes
/
resource.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
module Seota
class UnusableResource < Exception
def initialize(url)
super("#{url} is an unusable resource")
end
end
class Resource
def self.new_or_nil(url)
new(url)
rescue UnusableResource
nil
end
attr_reader :url, :uri
def initialize(url)
@url = url
@uri, @response = follow(url)
end
def [](header_key)
@response[header_key]
end
def body
@response.body
end
private
def follow(url)
uri = URI.parse(url)
response = Net::HTTP.get_response(uri)
if [Net::HTTPMovedPermanently, Net::HTTPFound].include?(response.class)
follow(response["location"])
elsif response.kind_of?(Net::HTTPSuccess)
[uri, response]
else
raise UnusableResource, url
end
end
def replace_path(new_path)
uri.to_s.sub(%r[#{uri.path}$], new_path)
end
end # Resource
end # Seota