-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscussion.rb
More file actions
72 lines (59 loc) · 1.59 KB
/
Copy pathdiscussion.rb
File metadata and controls
72 lines (59 loc) · 1.59 KB
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
require 'faraday'
require 'json'
class Discussion
class EngineUnreachableException < Exception; end
# TODO: If the same article comes in via multiple sources, uniq it
def self.of_articles(articles)
articles.map { |article|
self.for(article).map { |discussion|
discussion.article = article
discussion
}
}.flatten
end
def self.for(article)
article.identifier_strings.map do |identifier_string|
for_identifier(identifier_string)
end.flatten.uniq_by(&:url)
end
def self.for_identifier(identifier_string)
url = "#{PAPERNAUT_ENGINE_URL}/discussions.json?query=#{CGI.escape(identifier_string)}"
response = get_http(url)
discussion_hashes = JSON.parse(response.body)
discussion_hashes.map { |hash| self.new(hash) }
rescue JSON::ParserError => e
raise EngineUnreachableException.new
end
attr_accessor :article
def initialize(attributes)
@attributes = attributes
end
def title
if @attributes["title"] == @attributes["url"]
guess_readable_title_from_url
else
@attributes["title"]
end
end
def url
@attributes["url"]
end
def identifier_strings
@attributes["identifier_strings"] || []
end
private
def guess_readable_title_from_url
article_part = Addressable::URI.parse(url).path.split('/').last
pagename = article_part.underscore.humanize
end
def hostname
Addressable::URI.parse(url).host
end
def self.get_http(url)
begin
Faraday.get(url)
rescue Faraday::Error::ConnectionFailed => e
raise EngineUnreachableException.new
end
end
end