1

I would like to handle multiple URLs with one route code.

I am trying something like this:

get '/company', '/about' do 
  ...
end

but it does not work. For /company, I get 200, but for /about, I get 404.

Is there such way to do this?

sawa
  • 165,429
  • 45
  • 277
  • 381
Levi
  • 77
  • 7

1 Answers1

2

The route file is a ruby file. You can do this with a simple loop:

['/company', '/about'].each do |route|
  get route do
    # ...
  end
end

From the source code:

def get(path, *args, &block)
  conditions = @conditions.dup
  route('GET', path, *args, &block)

  @conditions = conditions
  route('HEAD', path, *args, &block)
end

You can see that the get method only takes a single path.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
  • Great this is working thanks, I was trying about sinatra style, but this is possibility too. Thank you – Levi May 30 '18 at 09:25
  • From the source code, it seems like path can also be a regexp, so `get %r{/(company|about)}` could work as well (haven't tried it). – Stefan May 30 '18 at 09:26
  • (Haven't tried it either, but) don't forget to anchor the regex with `^ ... $`! Otherwise you could hijack all sorts of other routes, like `/not/about/the/company`. – Tom Lord May 30 '18 at 09:39