lucky_router icon indicating copy to clipboard operation
lucky_router copied to clipboard

Allow setting regex for path parts

Open paulcsmith opened this issue 5 years ago • 2 comments

paulcsmith avatar Apr 05 '20 22:04 paulcsmith

This would be especially useful when a wildcard route unintentionally matches a static asset, leading to a 404 error.

For example:

class Products::Show < BrowserAction
  get "/:brand/:ref" do
    product = ProductQuery.new.brand(brand).ref(ref).first
    html ShowPage, product: product
  end
end

In this case, the route get "/:brand/:ref" matches /css/app.css, but no Product with the brand "css" and ref "app.css" exists, resulting in an Avram::RecordNotFoundError.

In Rails, this problem can be avoided by adding constraints on routes:

get "/:brand/:ref", to: "products#show", constraints: { brand: /^(?!css).*$/ }

In this discussion @jwoertink suggest the possibility to use annotations.

@[Lucky::RouteField(ignore: /^(?!css).*$/)]
get "/:brand/:ref" do
  html ShowPage
end

cristian-lsdb avatar Jan 28 '25 11:01 cristian-lsdb

I like that. I also wonder if we could use a regex directly in the path. But I think either approach would be nice to have!

paulcsmith avatar Jan 28 '25 16:01 paulcsmith