class MySinatraApp< Sinatra::Base
...
before do
puts 'hello from sinatra!'
end
...
end

I expectedly want the filter to run only on the requests starting with /streaming..., but, what surprises me, the filter runs on every request to the whole Rails app. What can I do with such a behaviour?
I can add a regexp filter after before, but I don't think it's a good style.

3 Answers
3

I'm surprised to see this happen too, but as it has I suppose it tells us that the filters are universal. Since they are, you might try using Sinatra::Namespace from the sinatra-contrib gem, e.g.

require 'sinatra/namespace'
class App < Sinatra::Base
register Sinatra::Namespace
namespace "/" do
before do
# this will only run within routes marked "/",
# which should also be prepended with the mounted route,
# so "/streaming/"
end
get "/?" do
# something here
end
end

I'm not entirely sure this will work, and it may mean that routes must include the trailing slash, so "/streaming/" not "/streaming" (there's surely a workaround) but at least it might solve the problem you have.

Update

I tested the code below and the filters only run for their own app's urls. It appears that even the namespace part isn't needed with this code either. I noticed you've specified the mount method, but that isn't part of Rack - which library are you using for that? rack-mount?

require 'rubygems'
require 'bundler'
Bundler.require
require 'sinatra'
require 'sinatra/namespace'
class StreamingApp < Sinatra::Base
register Sinatra::Namespace
namespace "/" do
before do
warn "Entering Streaming before filter"
end
get "/?" do
"Hello from the StreamingApp"
end
end
namespace "/something" do
before do
warn "Entering Streaming's /something before filter"
warn "request.path_info = #{request.path_info}"
end
get "/?" do
"Hello from StreamingApp something"
end
end
end
class OtherApp < Sinatra::Base
before do
warn "Entering OtherApp before filter"
warn "request.path_info = #{request.path_info}"
end
get "/" do
"Hello from the OtherApp"
end
end
app = Rack::URLMap.new(
"/streaming" => StreamingApp,
"/" => OtherApp
)
run app

and filters started to word as expected.
Allthough, I do not understand clearly why it is happening: according to this article, mount should just call match with :anchor => false, so the routes should be the same. But the behaviour differs.

thank you, that will certainly work, but I don't like to include that /streaming inside the Sinatra app. I'd like it to be reusable. Why should it depend on where it will be mounted?
–
roman.brodetskiJan 23 '13 at 19:43