Skip to content

Instantly share code, notes, and snippets.

@hashrocketeer
Created October 28, 2015 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hashrocketeer/1ce71473d701284b1b30 to your computer and use it in GitHub Desktop.
Save hashrocketeer/1ce71473d701284b1b30 to your computer and use it in GitHub Desktop.
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
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