Fly Me To The Moon! A Quick Trip To Getting Your Ruby Projects Web Ready
If you’re like me and relatively new to Ruby, you might be struggling with visualizing your Ruby project when simply testing it inside a Ruby rake console just like I do! If only there were a quick way to turn my Ruby code into a functioning web application with minimal effort… Wait, there is!
Meet Sinatra.
So what is Sinatra? Sinatra is a domain-specific language, better known as a DSL, allowing us to create fully-functional Ruby in minutes! Sinatra is based on Rack, allowing it to work seamlessly with Ruby. Simply, Sinatra is just a set of pre-written methods allowing us to make our applications web-ready. So how do we use it? First, you’ll need to install the gem.
gem install sinatra
You’ll also need to require Sinatra inside your Ruby application.
# myfrankapp.rb
require 'sinatra'
get '/' do
'Fly me to the moon!'
end
Next, run your application!
ruby myfrankapp.rb
You can check out your application in the browser at http://localhost:4567.
And that’s it. Wasn’t that easy? Well, you’re technically done but there’s plenty more to explore with Sinatra. Let’s take a look at one of the best pieces of Sinatra… Routing. We can take advantage of Sinatra’s built-in DSL to configure our routing
. If you know how to use React Router in React JS, this will look very familiar!
get '/' do
#show something
end
post '/' do
.. create something ..
end
patch '/' do
.. modify something ..
end
delete '/' do
.. annihilate something ..
end
We can also include params
in our routes
.
get '/hits/:title' do
# matches "GET /hits/foo" and "GET /hits/bar"
# params['title'] is 'foo' or 'bar'
"Frank Sinatra's best song is #{params['title']}!"
end
We can even use query parameters!
get '/hits' do
# matches "GET /hits?title=foo&album=bar"
title = params['title']
album = params['album']
# uses title and album variables to allow us pass query parameters to find Sinatra's hit titles and albums; query is optional to the /posts route
end
There is so much more you can check out and tweak that I didn’t cover in this blog post. If you’d like to take an even deeper dive into Sinatra, head on over to www.sinatrarb.com and take a look at their extremely detailed readme. And always, stay comfy: