Filtros

Before Filters

Before filters are evaluated before each request within the same context as the routes will be and can modify the request and response.

Instance variables set in filters are accessible by routes and templates:

before do
  @note = 'Hi!'
  request.path_info = '/foo/bar/baz'
end

get '/foo/*' do
  @note #=> 'Hi!'
  params[:splat] #=> 'bar/baz'
end

After Filters

After filters are evaluated after each request within the same context and can also modify the request and response.

Instance variables set in before filters and routes are accessible by after filters:

after do
  puts response.status
end
Note: Unless you use the body method rather than just returning a String from the routes, the body will not yet be available in the after filter, since it is generated later on.

Filters can take a Pattern

Filters optionally take a pattern, causing them to be evaluated only if the request path matches that pattern:
before '/protected/*' do
  authenticate!
end

after '/create/:slug' do |slug|
  session[:last_slug] = slug
end

Filters can take a Condition

Like routes, filters also take conditions:
before :agent => /Songbird/ do
  # ...
end

after '/blog/*', :host_name => 'example.com' do
  # ...
end



Subsecciones
Casiano Rodriguez León 2015-01-07