Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra routes regular expression alphanumeric

Tags:

regex

sinatra

#get "/blog/:title-:slug" do
#  erb :"/blog/#{params[:slug]}.html
#end

both :title and slug can be alphanumeric.

I am trying to make the url dynamic with regular expression.

get '/blog/*-*' do
    erb :"/blog/#{params['splat'][1]}.html"
end

I came up with the version above which uses a wildcard and that works but I am hoping to make the route more specific. I am currently struggling with what I have below after consulting the ruby regexp documentation.

# get '/blog\/[[:alnum:]]/-/[[:alnum:]]/' do
#   puts params['alnum']
#   erb :"/blog/#{params['alnum']}.html"
# end
like image 354
Jngai1297 Avatar asked Jan 24 '26 18:01

Jngai1297


1 Answers

Sinatra accepts regexp values as the parameter to route methods (get, post etc.), so the route can be rewritten as:

get %r{/blog/(\w+)-(\w+)} do
  ...
end

This will match all the routes that have alphabets or numbers. However, the captured values won't be available in the params object. To achieve that, you'd need to use the named captures syntax:

get %r{/blog/(?<title>\w+)-(?<slug>\w+)} do
  puts params[:title]
  puts params[:slug]
end

you can also use the unicode-aware [[:alnum:]] regexp matcher:

get %r{/blog/(?<title>[[:alnum:]]+)-(?<slug>[[:alnum:]]+)} do
  puts params[:title]
  puts params[:slug]
end
like image 187
Kashyap Avatar answered Jan 27 '26 00:01

Kashyap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!