Sinatra Basics : Sinatra Filters

Objective


To learn how to use before and after filters in Sinatra.

Steps


Step 1

Create filter.rb

require 'sinatra'

before do
  puts "Before called"
end

get '/' do
  'hello'
end

Step 2

bundle exec shotgun filter.rb

Step 3

Browse to http://localhost:9393/.

Browser output: hi
Server log output : Before called

Step 4

Add after filter:

after do
  puts 'after called'
end

so the file now looks like this:

require 'sinatra'

before do
  puts "Before called"
end

after do
  puts 'after called'
end

get '/' do
  'hello'
end

Step 5

Reload the browser.

Before called
after called

is seen in the server log.

Summary


In this article, you learned how to use before and after filter in a Sinatra application.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.