Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra: before filter ordering

Tags:

ruby

sinatra

I want to define a global before filter that will run before every request that will set up some instance variables for all the methods.

I have set up the filter and have also set up some route specific before filters. It appears that my route specific filters are being executed prior to my global one and therefore crashing because expected instance variables are not set yet.

Is there a way to specify the order in which before filters are processed?

like image 228
jasonlfunk Avatar asked Apr 21 '26 02:04

jasonlfunk


1 Answers

This works for me, on Sinatra 1.3.2.

before do
  @filter = [] << 'everything'
end
before '/filter' do
  @filter << 'specific'
end
get '/filter' do
  @filter.inspect
end

This gives me ["everything", "specific"] which is what I would expect. Is it possible you do not have the catch-all filter before all the rest?

In Sinatra, routes are evaluated in order from the top, not by how well they match. Therefore, if you have the specific filters before the catch-all filter, it will evaluate those first, as seen here:

before '/filter' do
  @filter = [] << 'specific'
end
before do
  @filter << 'everything'
end
get '/filter' do
  @filter.inspect
end    # => ["specific", "everything"]
like image 169
Paul Hoffer Avatar answered Apr 22 '26 15:04

Paul Hoffer



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!