Skip to content

Instantly share code, notes, and snippets.

@jwashke
Last active March 21, 2016 20:46
Show Gist options
  • Save jwashke/4fedcb65ea0b49dffbc4 to your computer and use it in GitHub Desktop.
Save jwashke/4fedcb65ea0b49dffbc4 to your computer and use it in GitHub Desktop.

Sinatra

  • Ruby gem
  • Domain-specific language (DSL)
  • minimal effort Ruby library that makes HTTP access and simple web apps easy
  • Much more light weight than rails so more suitable for smaller simpler applications.

Things about Sinatra

  • modular vs classic style
  • Rack-compatible
  • config.ru file

Web Guesser File structure

Mimics Rails organizational structure using MVC (Model, View, Controller)

  • Sinatra project folder
    • Server file
    • Views folder
      • erb files

Server File

  • Contains routing with HTTP verbs (GET, POST, PUT, DELETE)
  • Client says GET me something from...
    • example.com/ --> get '/'
    • example.com/people --> get '/people'
    • example.com/posts --> get '/posts'
  • What you put in your server file determines what the client gets back.

Routing in Server file

get '/' do
  #stuff to be done
  erb :index # which erb file to render
end

Sending Variables to Views

Instance Variables
get '/' do
  @number = 8
  erb :index
end
Local Variables
get '/' do
  number = 8
  erb(:index, locals => { :variable_in_view => variable_in_server })
  # the key :variable_in_view is the name of the variable in the 
  # erb file the value it is pointing to is the actual variable you 
  # want to send.
end

Views in Sinatra

  • Server file specifies which view to send back to client
  • Views are .erb files (Embedded RuBy)
  • Interprets any ruby and sends back pure HTML to client
embed Ruby code in HTML using the below syntax

<% ruby_code_here %>

embed Ruby code you want display in HTML using the below syntax

<%= ruby_code_here %>

Example HTML with ERB
    <html>
      <head>
      </head>
      <body>
        <%= ruby_variable %>
      </body>
    </html>

Forms in HTML

    <form>
      <input type="text" name="firstname">
      <input type="text" name="lastname">
      <input type="submit" value="Click here!">
    </form>

Data submitted by user in a form comes in as a hash called "params"
The input the user typed on line 2 can be accessed in your server file as params[:firstname]
The input the user typed on line 3 can be accessed in your server file as params["lastname"]

  • notice that you can use strings or symbols for your key names
Accessing Params in Routes
    get '/dashboard' do
      @name = params["firstname"]
      erb :dashboard
    end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment