Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'typhoeus'
require 'json'
# 1. Get data from http
# 2. Parsing JSON
# 3. Calculate score
# 4. Show score
class Http
attr_reader :client
def initialize(client = Typhoeus)
@client = client
end
def get(url)
client.get(url).body
end
end
class Github
BASE_URI = "https://api.github.com"
attr_reader :http
def initialize(http: Http.new)
@http = http
end
def events(user)
parse http.get(URI.join(BASE_URI, "/users/#{user}/events/public"))
end
private
def parse(body)
json(body).map { |entry| OpenStruct.new(entry) }
end
def json(body)
JSON.parse(body)
end
end
class ScoreSet
include Enumerable
attr_reader :scores
def initialize(scores)
@scores = scores
end
def each(&block)
@scores.each(&block)
end
def for(name)
find { |s| s.name == name } || Score.new(name, 1)
end
end
class Score
attr_reader :name, :weight
def initialize(name, weight)
@name = name
@weight = weight
end
end
class CalculateUserScore
def initialize(events, score_set)
@events = events
@score_set = score_set
end
def call
@events.map { |e| @score_set.for(e.type) }.sum(&:weight)
end
end
scores = ScoreSet.new([
Score.new("IssuesEvent", 7),
Score.new("IssueCommentEvent", 6),
Score.new("PushEvent", 5),
Score.new("PullRequestReviewCommentEvent", 4),
Score.new("WatchEvent", 3),
Score.new("CreateEvent", 2),
])
events = Github.new.events("dhh")
puts CalculateUserScore.new(events, scores).call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment