Beginner’s Sinatra
                                Minimal Framework in Ruby




2012/09/22 - kanazawa.rb #2
Web System

   Web server



Application server



Database server
Web System
                     Client
   Web server



Application server



Database server
example
Web System

  Apache



Tomcat (java)



 PostgreSQL
example
Web System

    nginx



 Rails (Ruby)



   MySQL
example
Web System

     thin



Sinatra (Ruby)



   MySQL
example
Web System

     thin



Sinatra (Ruby)



   MySQL
Sinatra
Sinatra

http://www.sinatrarb.com
Sinatra

http://www.sinatrarb.com



        Sinatra is a DSL for
          quickly creating
     web applications in Ruby
Sinatra

http://www.sinatrarb.com



        Sinatra is a DSL for
         quickly creating
     web applications in Ruby
Hello world!


$ gem install sinatra

$ vi myapp.rb

$ ruby myapp.rb
Hello world!


$ gem install sinatra

$ vi myapp.rb

$ ruby myapp.rb
Hello world!

require 'sinatra'


get '/' do
 'Hello world!'
end
Hello world!

require 'sinatra'


get '/' do
 'Hello world!'
end
                    that's all
Hello world!

require 'sinatra'


get '/' do
 'Hello world!'
end
Hello world!

          require 'sinatra'
Request

          get '/' do
           'Hello world!'
          end
Hello world!

          require 'sinatra'
Request

          get '/' do
           'Hello world!'
          end          Handling & Response
Hello world!


$ gem install sinatra

$ vi myapp.rb

$ ruby myapp.rb
Hello world!
Hello world!
MVC



Model
View
Controller
MVC



Model
View
Controller
MVC



Model
View           Sinatra
Controller
MVC



Model
View
Controller
MVC

               ActiveRecord
               DataMapper
                  Sequel
Model
View
Controller
MVC

               ActiveRecord
               DataMapper
                  Sequel
Model
View
                     erb
Controller          haml
                   Builder
MVC

                ActiveRecord
                DataMapper
                   Sequel
Model
View
                     erb
Controller          haml
                   Builder


        As you like :)
Sinatra

Minimal “Routing” Framework in Ruby



            handling     response

request     handling     response

            handling     response
Routing
How to routing


1.HTTP method + URL path
2.Conditions
3.Filters
4.Passing
5.Halt & Error
1. HTTP method + URL path


HTTP method
  get
  post
  put
  delete
1. HTTP method + URL path

get '/' do ...

post '/' do ...

put '/' do ...

delete '/' do ...
                     first match
1. HTTP method + URL path



URL path
  pattern
  regular expressions
1. HTTP method + URL path

get '/path/' do ... # => '/path/'

get '/path/:dir/:file' do ... # => '/path/hoge/fuga'

get '/path/*.*' do ... # => '/path/hoge.xml'

get %r{/path/[w]+} do ... # => '/path/hoge'
                                           first match
2. Conditions


user agent
host name
mime type (≒HTTP Accept)
custom conditions
2. Conditions


get '/', :agent => /MSIE/ do ...

get '/', :host_name => /^admin./ do ...

get '/', :provides => :rss do ...

                                           first match
2. Conditions


set(:random) { |val| condition { rand <= val } }


get '/', :random => 0.2 do ... # => 20%
get '/' do ... # => 80%

                                          first match
3. Filters



Before
After
3. Filters


before '/usr/*' do ...
before '/' do ...
get '/usr/*' do ...
get '*' do ...
after '/usr/*' do ...
after do ... # => after '*' do ...
3. Filters

                                 /usr/hoge

before '/usr/*' do ...
before '/' do ...
get '/usr/*' do ...
get '*' do ...
after '/usr/*' do ...
after do ... # => after '*' do ...
3. Filters

                                 /usr/hoge

before '/usr/*' do ...               1
before '/' do ...
get '/usr/*' do ...                  2
get '*' do ...
after '/usr/*' do ...                3
after do ... # => after '*' do ...
3. Filters

                                 /usr/hoge   /

before '/usr/*' do ...               1
before '/' do ...
get '/usr/*' do ...                  2
get '*' do ...
after '/usr/*' do ...                3
after do ... # => after '*' do ...
3. Filters

                                 /usr/hoge   /

before '/usr/*' do ...               1
before '/' do ...                            1
get '/usr/*' do ...                  2
get '*' do ...                               2
after '/usr/*' do ...                3
after do ... # => after '*' do ...           3
3. Filters

                                 /usr/hoge   /   /fuga

before '/usr/*' do ...               1
before '/' do ...                            1
get '/usr/*' do ...                  2
get '*' do ...                               2
after '/usr/*' do ...                3
after do ... # => after '*' do ...           3
3. Filters

                                 /usr/hoge   /   /fuga

before '/usr/*' do ...               1
before '/' do ...                            1
get '/usr/*' do ...                  2
get '*' do ...                               2    1
after '/usr/*' do ...                3
after do ... # => after '*' do ...           3    2
4. Passing

get '*' do
  pass if rand <= 0.2;
  # xxx
end
get '*' do
  # xxx
end
                                 first match
4. Passing

get '*' do
  pass if rand <= 0.2;
  # xxx
end
get '*' do
  # xxx
end
                                 first match
5. Halt & Error


error 403 do
  'Access Forbidden'
end
before '/secret/*' do
  halt 403 unless authorized
end
5. Halt & Error


error 403 do
  'Access Forbidden'
end
before '/secret/*' do
  halt 403 unless authorized
end
5. Halt & Error


error 404 do
  'File Not Found'
end
before '/devel/*' do
  halt 'xxx'
end
Request
URL pattern (:xxx)



get '/path/:dir/:file' do # => '/path/hoge/fuga'
  params[:dir] # => "hoge"
  params[:file] # => "fuga"
end
URL pattern (*)

get '/path/*.*' do # => '/path/hoge/fuga.xml'
  params[:splat] # => [ "hoge/fuga", "xml" ]
end
get '/path/*.*' do |path, ext| # => '/path/hoge/fuga.xml'
  path # => "hoge/fuga"
  ext # => "xml"
end
URL regular expression


get %r{/path/([w]+)} do # => '/path/hoge'
  params[:capture] # => [ "hoge" ]
end
get %r{/path/([w]+)} do |cap| # => '/path/hoge'
  cap # => [ "hoge" ]
end
HTTP Get query


"/?abc=hoge&def=fuga"


get '*' do
  params[:abc] # => "hoge"
  params[:def] # => "fuga"
end
HTTP Post data

<input name="abc" value="hoge">
<input name="def" value="fuga">


post '*' do
  params[:abc] # => "hoge"
  params[:def] # => "fuga"
end
request object


get '*' do
  request.cookies # => cookie hash
  request.xhr? # => is ajax request (boolean)
  request.methods # => any more!
end
Response
Response type



1.Objects
2.Template
1. Object


String
Fixnum (as HTTP Status code)
Array
   [status (Fixnum), response body (responds to #each)]
   [status (Fixnum), headers (Hash), response body (responds to #each)]
2. Template

haml
erb
builder
2. Template

haml
erb
builder
sass
coffee-script
2. Template



get '/' do
 erb :index # => ./views/index.erb
end
2. Template



get '/' do
 erb :index # => ./views/index.erb
end
2. Template



get '/' do
 erb :index # => ./views/index.erb
end
                    config OK
2. Template

get '/' do
  @attr1 = "val1"
  @attr2 = "val2"
  erb :index
end


<%= @attr1 %><%= @attr2 %>
2. Template


get '/' do
  erb :index, :locals => { :attr1 => "val1", :attr2 => "val2" }
end




<%= attr1 %><%= attr2 %>
Conclusion
Sinatra


Minimal   routing framework

for   quickly creating web applications in Ruby

can using   any templates
Thank you




Tomokazu Kiyohara
http://facebook.com/tomokazu.kiyohara
http://twitter.com/kiyohara

More Related Content

PDF
Ruby - Uma Introdução
PDF
Sinatra Rack And Middleware
PDF
App Lego
KEY
PDF
My Robot Poops - In JavaScript (with web sockets)
KEY
An introduction to Ruby
KEY
Your Library Sucks, and why you should use it.
KEY
Sinatra for REST services
Ruby - Uma Introdução
Sinatra Rack And Middleware
App Lego
My Robot Poops - In JavaScript (with web sockets)
An introduction to Ruby
Your Library Sucks, and why you should use it.
Sinatra for REST services

What's hot (20)

PDF
Chef Workshop: Setup Environment with Chef,Vagrant, and Berkshelf
PDF
ES6 - Level up your JavaScript Skills
PDF
Using Buildout to Develop and Deploy Python Projects
PDF
Intro to Rails
KEY
Using Sinatra as a lightweight web service
PDF
Having Fun Programming!
ODP
Modern Perl
ODP
Moose - YAPC::NA 2012
KEY
jQuery Anti-Patterns for Performance & Compression
PDF
Effective ES6
PDF
ES6 in Production [JSConfUY2015]
PPT
All That Jazz
KEY
A tour on ruby and friends
ZIP
Ruby Kaigi 2008 LT
ODP
Evolving Software with Moose
PDF
Bologna Developer Zone - About Kotlin
PPTX
Pry, the good parts
PDF
Unleash your inner console cowboy
PDF
Vagrant for real
Chef Workshop: Setup Environment with Chef,Vagrant, and Berkshelf
ES6 - Level up your JavaScript Skills
Using Buildout to Develop and Deploy Python Projects
Intro to Rails
Using Sinatra as a lightweight web service
Having Fun Programming!
Modern Perl
Moose - YAPC::NA 2012
jQuery Anti-Patterns for Performance & Compression
Effective ES6
ES6 in Production [JSConfUY2015]
All That Jazz
A tour on ruby and friends
Ruby Kaigi 2008 LT
Evolving Software with Moose
Bologna Developer Zone - About Kotlin
Pry, the good parts
Unleash your inner console cowboy
Vagrant for real
Ad

Viewers also liked (9)

PDF
Sinatraで鼻歌まじりのWeb開発
PDF
«Работа с базами данных с использованием Sequel»
PPTX
Ruby object model
KEY
Advanced Ruby Idioms So Clean You Can Eat Off Of Them
PDF
Object-Oriented BDD w/ Cucumber by Matt van Horn
PPT
Ruby For Java Programmers
PDF
Ruby on Rails for beginners
PDF
How to Teach Yourself to Code
PDF
Ruby for Java Developers
Sinatraで鼻歌まじりのWeb開発
«Работа с базами данных с использованием Sequel»
Ruby object model
Advanced Ruby Idioms So Clean You Can Eat Off Of Them
Object-Oriented BDD w/ Cucumber by Matt van Horn
Ruby For Java Programmers
Ruby on Rails for beginners
How to Teach Yourself to Code
Ruby for Java Developers
Ad

Similar to Beginner's Sinatra (20)

KEY
Sinatra事始め
KEY
Crafting Beautiful CLI Applications in Ruby
KEY
API Design
KEY
Rails Presentation (Anton Dmitriyev)
PDF
Ruby 入門 第一次就上手
PDF
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
PDF
Ruby talk romania
PDF
Connecting the Worlds of Java and Ruby with JRuby
PDF
Play vs Rails
KEY
Picking gem ruby for penetration testers
PDF
Ruby on Rails
PDF
Ruby projects of interest for DevOps
PDF
Ricardo Sanchez - Ruby projects of interest for devops
PDF
The basics of fluentd
PDF
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
PDF
Ruby and Rails by Example (GeekCamp edition)
PDF
Ruby on rails探索
PDF
Vaporware To Awesome
PDF
O que tem de novo no Ruby 2.0?
PPTX
RoR guide_p1
Sinatra事始め
Crafting Beautiful CLI Applications in Ruby
API Design
Rails Presentation (Anton Dmitriyev)
Ruby 入門 第一次就上手
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Ruby talk romania
Connecting the Worlds of Java and Ruby with JRuby
Play vs Rails
Picking gem ruby for penetration testers
Ruby on Rails
Ruby projects of interest for DevOps
Ricardo Sanchez - Ruby projects of interest for devops
The basics of fluentd
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Ruby and Rails by Example (GeekCamp edition)
Ruby on rails探索
Vaporware To Awesome
O que tem de novo no Ruby 2.0?
RoR guide_p1

More from Tomokazu Kiyohara (15)

PDF
JavaScript で OS X を自動操作
PDF
Google Cloud Platform を支える技術 …のごく一部
PDF
イベント継続のコツ
PDF
Web API をデバックするときに必要なたったひとつのこと
PDF
明日から使えるコーディングツール
PDF
Atom.io Quick Scripting
PDF
Text-Objects - vim's elegant function
PDF
LiveStyle for Vim - Quick start
PDF
こわくないプルリク
PDF
Github's HUB
PDF
対サイバー攻撃アラートシステム “DAEDALUS”(ダイダロス)の紹介
KEY
Compact Web - Remind "web compression" -
KEY
Zen coding15min
KEY
USTREAMの視聴率を上げよう!
KEY
JavaScript Dynamic Loading
JavaScript で OS X を自動操作
Google Cloud Platform を支える技術 …のごく一部
イベント継続のコツ
Web API をデバックするときに必要なたったひとつのこと
明日から使えるコーディングツール
Atom.io Quick Scripting
Text-Objects - vim's elegant function
LiveStyle for Vim - Quick start
こわくないプルリク
Github's HUB
対サイバー攻撃アラートシステム “DAEDALUS”(ダイダロス)の紹介
Compact Web - Remind "web compression" -
Zen coding15min
USTREAMの視聴率を上げよう!
JavaScript Dynamic Loading

Recently uploaded (20)

PDF
Lung cancer patients survival prediction using outlier detection and optimize...
PDF
Statistics on Ai - sourced from AIPRM.pdf
PDF
4 layer Arch & Reference Arch of IoT.pdf
PDF
Co-training pseudo-labeling for text classification with support vector machi...
PDF
Auditboard EB SOX Playbook 2023 edition.
PDF
INTERSPEECH 2025 「Recent Advances and Future Directions in Voice Conversion」
PPTX
Internet of Everything -Basic concepts details
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PPTX
Training Program for knowledge in solar cell and solar industry
DOCX
search engine optimization ppt fir known well about this
PPTX
Microsoft User Copilot Training Slide Deck
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PDF
Accessing-Finance-in-Jordan-MENA 2024 2025.pdf
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
PPTX
AI-driven Assurance Across Your End-to-end Network With ThousandEyes
PDF
NewMind AI Weekly Chronicles – August ’25 Week IV
PDF
giants, standing on the shoulders of - by Daniel Stenberg
PPTX
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
Lung cancer patients survival prediction using outlier detection and optimize...
Statistics on Ai - sourced from AIPRM.pdf
4 layer Arch & Reference Arch of IoT.pdf
Co-training pseudo-labeling for text classification with support vector machi...
Auditboard EB SOX Playbook 2023 edition.
INTERSPEECH 2025 「Recent Advances and Future Directions in Voice Conversion」
Internet of Everything -Basic concepts details
Enhancing plagiarism detection using data pre-processing and machine learning...
Training Program for knowledge in solar cell and solar industry
search engine optimization ppt fir known well about this
Microsoft User Copilot Training Slide Deck
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
Accessing-Finance-in-Jordan-MENA 2024 2025.pdf
Rapid Prototyping: A lecture on prototyping techniques for interface design
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
AI-driven Assurance Across Your End-to-end Network With ThousandEyes
NewMind AI Weekly Chronicles – August ’25 Week IV
giants, standing on the shoulders of - by Daniel Stenberg
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION

Beginner's Sinatra

Editor's Notes