Created
October 28, 2015 19:11
-
-
Save hashrocketeer/1ce71473d701284b1b30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PathFinder | |
attr_reader :paths | |
def initialize(paths) | |
@paths = paths | |
end | |
def find(request_path) | |
find_path(request_path) or fail ActiveRecord::RecordNotFound | |
end | |
def find_path(request_path) | |
paths.to_a.find do |path| | |
request_path.match path_regex(path.name) | |
end | |
end | |
def path_regex(path_name) | |
Sinatra::Base.send(:compile, path_name).first | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rails_helper" | |
describe PathFinder do | |
before do | |
Fabricate(:path, name: "users") | |
Fabricate(:path, name: "users/:user_id") | |
end | |
let(:paths) { Path.all } | |
subject { described_class.new(paths) } | |
describe "#find" do | |
it "finds the exact match" do | |
expect(subject.find("users").name).to eq("users") | |
end | |
it "finds path with the colon(:) syntax" do | |
expect(subject.find("users/6").name).to eq("users/:user_id") | |
end | |
it "fails when not found" do | |
expect { subject.find("foo/bar") }.to raise_error ActiveRecord::RecordNotFound | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment