Parameters

Parameters are to url's what variables are to code. You need more than a domain name to transfer information between a user and a website. For example if a user visiting a blog want to filter posts for a specific category, it can be passed as a parameter to the url.

http://www.blog.com?category=ruby

Before we start with writing more code let's quickly add shotgun to our Gemfile. Shotgun ensures that our application server is automatically reloaded every time we make changes to our app.rb

source 'https://rubygems.org'

gem 'sinatra'
gem 'shotgun'

After making changes to the Gemfile go ahead and run bundle install once. We can now load shotgun by using the following command

~/w/hello ❯❯❯ shotgun app.rb
== Shotgun/WEBrick on http://127.0.0.1:9393/
[2017-04-01 00:48:53] INFO  WEBrick 1.3.1
[2017-04-01 00:48:53] INFO  ruby 2.4.0 (2016-12-24) [x86_64-darwin15]
[2017-04-01 00:48:53] INFO  WEBrick::HTTPServer#start: pid=97400 port=9393

Sinatra manages parameters using the params hash. Let's add a new route to our app.rb.

get '/greet' do  
  name = params[:name]
  return "Hello #{name}"
end

This will add a route '/greet' to our application and return a customized Hello message. Go to your browser and enter http://localhost:9393/greet?name=John

What happens if you do not pass a parameter? It will simply return "Hello" which is fine but there might be a route where a parameter is mandatory. Since our app.rb is plain ruby we can very easily add that validation to our code.

get '/greet' do
  # http://localhost:9393/greet?name=karim
  name = params[:name]
  if name!=nil
    return "Hello #{name}"
  else
    return "Invalid Parameters"
  end
end

Note: nil is not empty!


We will add one more route /print_params that will print all the parameters passed to it.

get '/print_params' do
  params.to_s
end

Let's test this code by visting http://localhost:9393/print_params?name=John&age=32&weight=66


Lab

  1. Add a route /fibo that requires a parameter 'n'. Display the n'th Fibonacci number to the user. Example: When a user visits http://localhost:9393/fibo?n=5, the app should display The 5th fibonacci number is 3.

  2. Push your code to Github. [git add ., git commit -m "parameters in sinatra", git push origin master]

results matching ""

    No results matching ""