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
|
#!/usr/bin/env ruby
require 'net/http'
require 'uri'
require 'json'
require 'rspec/autorun'
require 'webmock/rspec'
class UserNotFound < ArgumentError
end
class GithubScore
DEFAULT_POINTS = {
"IssuesEvent" => 1,
"IssueCommentEvent" => 2,
"PushEvent" => 3,
"PullRequestReviewCommentEvent" => 4,
"WatchEvent" => 5,
"CreateEvent" => 6
}.freeze
def initialize(handle, points: DEFAULT_POINTS)
@handle = handle
@points = points
end
def score
calculate_score_for(events)
end
private
attr_reader :points, :handle
def build_url
"https://api.github.com/users/#{handle}/events/public"
end
def events
response = Net::HTTP.get_response(URI.parse(build_url))
raise UserNotFound.new(handle) if response.code == "404"
JSON.parse(response.body)
end
def calculate_score_for(events)
grouped = events.group_by { |h| h["type"] }.values
score = grouped.map { |g|
event_type = g.first["type"].strip
event_score = points[event_type] || 1
event_score * g.count
}.sum
score
end
end
RSpec.describe GithubScore do
describe "#score" do
subject(:github_score) { GithubScore.new(handle) }
let(:handle) { "tenderlove" }
context "when calculating the score for a known user" do
let(:events) { [{type: 'PushEvent'}, {type: 'IssuesEvent'}] }
before do
stub_request(:get, "https://api.github.com/users/#{handle}/events/public")
.to_return(status: 200, body: events.to_json)
end
it { expect(github_score.score).to eq(4) }
end
context "when attempting to retrive the score for an unknown user" do
before do
stub_request(:get, "https://api.github.com/users/#{handle}/events/public")
.to_return(status: 404, body: {
"message": "Not Found",
"documentation_url": "https://docs.github.com/rest/reference/activity#list-public-events-for-a-user"
}.to_json)
end
it { expect { github_score.score }.to raise_error(UserNotFound) }
end
# it times out
end
end
|