Skip to content

Instantly share code, notes, and snippets.

@dzucconi
Created February 17, 2016 16:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dzucconi/b87ea7c06cf38765cf28 to your computer and use it in GitHub Desktop.
class Redirector
FALLBACK = '/'
def self.url(a)
match(a)[:key]
end
def self.handle(url)
RedirectTable::MAP[url] || url(url) || FALLBACK
end
private
def self.distance(a, b)
[(0..a.size).to_a].tap { |mx|
(1..b.size).each do |j|
mx << [j] + [0] * (a.size)
end
(1..b.size).each do |i|
(1..a.size).each do |j|
mx[i][j] = if a[j - 1] == b[i - 1]
mx[i-1][j-1]
else
[mx[i-1][j], mx[i][j-1], mx[i-1][j-1]].min + 1
end
end
end
}[-1][-1]
end
def self.keys
@client ||= Client.new cache: true
@sidebar ||= Sidebar.new @client
@sidebar.links.map(&:href)
end
def self.match(a)
keys.map { |key| { key: key, distance: distance(a, key) } }.min_by { |hsh| hsh[:distance] }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment