Building Web Applications with Sinatra
Reading
Making our first web app
Sinatra
Gem for producing web applications
Install with
gem install sinatra sinatra-contrib
Initial sinatra (hello world) app
require 'sinatra'get '/' do"Hello, World"endBreaking down the sinatra code
require 'sinatra'
- require the sinatra libraryget '/' do
- defines a block of code to run whenever weGET
the/
URL"Hello World"
- Whatever the block returns returns becomes the body of the pageLet's make an APP
require 'sinatra'require 'sinatra/json'get '/' dojson ['hello', 'world']end
Parsing parameters
How can we send information to our application
Simplest way is via query parameters
We can tack these on to the end of our URLS:
http://localhost:4567?item=3
ITEMS = ["Pick up laundry","Finish Homework","Cook Dinner","Read Book",]get '/item' donumber = params["number"].to_ijson item: ITEMS[number]endCan also supply them in the URL
get '/items/:id' doid = params["id"].to_ijson item: ITEMS[id]end
Let's put or items into a database
Combining
SQL
+activerecord
+sinatra
Let's add the 'activerecord' gem to our sinatra app
require 'active_record'
Let's create a database:
createdb itemsThen lets create a table to store our items. We'll name the column
text
to store the text of the item. We'll also add a boolean to mark if it is complete.CREATE TABLE items(id serial, text text, complete bool);Let's update our app to show us the items in our database
require 'active_record'require 'sinatra'require 'sinatra/json'ActiveRecord::Base.establish_connection(adapter: "postgresql",database: "items")class Item < ActiveRecord::Baseend# Get one itemget '/items/:id' doitem_from_database = Item.find(params["id"])json item: item_from_databaseendThen lets create an endpoint to show all the items
# Get all the itemsget '/items' doall_items = Item.alljson items: all_itemsendLet's add an endpoint to create a item
# Create one itempost '/items' doitem_params = params["item"]new_item = Item.create(item_params)json item: new_itemendAnd an endpoint to update a item
# Update a itemput '/items/:id' doitem_params = params["item"]existing_item = Item.find(params["id"])existing_item.update(item_params)json item: existing_itemendAnd an endpoint to delete a item
# Delete a itemdelete '/items/:id' dodeleting_item = Item.find(params["id"])deleting_item.destroyjson item: deleting_itemend
Disabling CORS
to allow a React front end to connect to this app
- First install this gem:
gem install rack-cors
Then add this code before our first get
/post
/put
/delete
# Allow anyone to access our API via a browseruse Rack::Cors do |config|config.allow do |allow|allow.origins '*'allow.resource '*'endend
This is the beginning of our introduction to the concepts of REST (REpresentational State Transfer)
Tired of stopping and starting Sinatra after each code change?
- Install the
sinatra-contrib
gem and use thereloader
it providesgem install sinatra-contrib
require 'sinatra/reloader' if development?