Named Parameters

What are parameters?

Simply, they’re bits of information that come from the client (or browser). Simply, it’s data sent by the user to your web application. There’s typically two types of parameters sent

  • A querystring parameter: If you’ve ever looked at a google search URL it’s normally something like http://google.com/?q=lolcatz. You see there’s a ? at the end of the url. This denotes the start of a querystring. Then you’ll get the name of the piece of information followed by an = and then the piece of information that’s being passed.

  • POST Data: Some data is sent differently though. Normally when you submit a form it’s sent as a HTTP POST request. In this case, the parameters are encoded in the HTTP request itself (they don’t show up in the URL of the page being called).

In any case you can access the information the same way in your action: using the params object.

Params

The params are really just a series of key-value pairs where the key and the value are strings. Keep in mind, this means you might need to convert an outcome to a number value to use it in your program.

An example

If we had a URL: http://ourserver.com/action?name=bob&say=hello

We would have two named parameters ‘name’ and ‘say’ and we could access the parameters like this


get '/action' do 

	name = params[:name] 
	say = params[:say] 

end

And we would have received ‘bob’ and ‘hello’ respectively.

Routing parameters

In addition to the user defined parameters mentioned above, we can also specify parameters we want to require as part of our routes i.e. they’ve got to be included in the URL we want to call. These parameters are accessible as part of the params hash just like normal.

Parameters

For example:

get '/hello/:name' do
  # matches "GET /hello/jane" and "GET /hello/sally"
  # params['name'] is 'jane' or 'sally'
  "Hello #{params['name']}!"
end

Here we have a route where anything after ‘/hello/’ will be contained in a params array with the key :name.

In the browser, go to, for example, http://localhost:80/hello/dan and you should see the name displayed back (“dan”).

You could incorporate the :name into a string by wrapping it in #{…}. Try replacing the params[:name] line with:

"Hello there, #{params[:name]}."

As you’d expect, we can use all the normal Ruby string methods on the variable, such as .upcase, .reverse etc.

"Hello there #{params[:name].upcase}.”

You can set the route to accept multiple query string variables like so:

get '/hello/:name/:city' do
  "Hey there #{params[:name]} from #{params[:city]}."
end
×

Subscribe

The latest tutorials sent straight to your inbox.