0

I have the following route:

get '/:id', to: 'articles#show'

How do I have the route only match if the :id is a base64 encoded string? I've tried regexp unsuccessfully.

EDIT: I've tried using the regex suggested in one of the responses.

get /:id, to: 'articles#show', constraints: { id: /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/}

This leads to the following error in Rails:

Regexp anchor characters are not allowed in routing requirements:
/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/
GeekJock
  • 10,376
  • 12
  • 40
  • 44
  • I think it would be perhaps easier to check that in the controller. You could use a before_action filter and implement a method such as in this answer https://stackoverflow.com/questions/30476873/check-if-string-is-base64 – cesartalves Jan 27 '21 at 17:07
  • Think it's possible to create custom route constraints as an alternative to using regex. https://guides.rubyonrails.org/routing.html#advanced-constraints – Arnis Lapsa Jan 28 '21 at 05:34

1 Answers1

1

From the Rails routing guide located at https://guides.rubyonrails.org/v2.3.11/routing.html

get '/:id', to: 'articles#show', requirements: {id: **Your Regex**}

This route would only hit if the :id parameter hit on the Regex.

As for a regex that will successfully match a base64 string, answers to the following StackOverflow question provide lots of options. RegEx to parse or validate Base64 data

Update: Remove the anchor characters from your Regex. Source: Rails custom route with constraints - regexp anchor characters are not allowed in routing requirements