SlideShare a Scribd company logo
1 of 62
REST with Sinatra
  Emanuele DelBono
      @emadb
Thanks to the sponsors
About me
I’m a software developer in
CodicePlastico.
I write Web applications in C# with
ASP.NET MVC. I’m a member of
<WEBdeBS/> a local web
community.
...and I’m a wannabe Ruby
developer ;-)
Agenda
‣ Philosophy.
 Sweet and easy.
‣ REST.
 Yet another boring introduction.
‣ Hello world.
 Show some magic.
‣ Features.
 Amazing!
‣ Inside.
 How it works?
‣ Q&A.
 ...and thanks.
Sinatra as a REST server
What is isn’t
‣ Sinatra is not
 -another MV* framework
 -a full framework like Rails
 -an ORM
 -a game project
Sinatra is just a DSL
   written in ruby
Hello world
Hello world
~$ gem install sinatra
~$ vi app.rb
Hello world
~$ gem install sinatra
~$ vi app.rb

require 'sinatra'
get '/' do
 'hello world!'
end
Hello world
~$ gem install sinatra
~$ vi app.rb

require 'sinatra'
get '/' do
 'hello world!'
end

~$ ruby app.rb
Is it really so easy?
‣ Yep! (special thanks to Ruby
  sweeties)
  - get is a just a method (more later)
  - the route is the parameter
  - the block is what should be
    executed
  - the block returns the result
  - the server is built in (based on Rack)
Let’s go REST


What? Yet another REST introduction?
5 REST principles
‣ Uniform Interface
    ‣ HATEAOS
‣   Stateless
‣   Cacheable
‣   Client-Server
‣   Layered System
Sinatra and REST
‣ Sinatra supports
  - All HTTP verbs
  - Caching
  - Content types
  - Routes
  - ....and all you need to build a rest server
Give a look at the
Verbs
‣ Support for all verbs
  - Get, Post, Put, Delete, Head, Options,
    Patch


‣ They are just methods
Routing
‣ No need of route files or route
  maps
‣ The verb method takes the route
  as parameter
Routing


get ( ‘/todos’ ) {...}
get ( ‘/todo/:id’ ) {...}
get ( ‘/*’ ) {...}
Routing Conditions
get '/foo', :agent => /Mozilla/(d.d)s
w?/ do
 "You're using Mozilla version
#{params[:agent][0]}"
end
get '/foo' do
 # Matches non-Mozilla browsers
end
Routing Custom
set(:prob) { |v| condition { rand <= v } }

get '/win_a_car', :prob => 0.1 do
 "You won!"
end

get '/win_a_car' {"Sorry, you lost."}
Xml or Json
‣ You can set the content_type to
  whatever you need



content_type :json
content_type :xml
Status codes
‣ Set the HTTP status code is


  status 200
  status 403
Http Headers
‣ You can add your own headers


headers "X-My-Value" => "this is my
header"
Redirect


redirect to ‘/todos’
Cache
‣ You can set your cache information
  using the headers method

headers "Cache-Control" => "public,
must-revalidate, max-age=3600",
"Expires" => Time.at(Time.now.to_i + (60
Cache
‣ Or better, you can use the expires


expires 3600, :public
Filters
before do
 #...
end
after do
 #...
Authentication


‣ Basic authentication support through
  Rack
‣ Key-based authentication
Basic Authentication

use Rack::Auth::Basic, "Private area" do
|usr, pwd|
 [usr, pwd] == ['admin', 'admin']
end
Token authentication
before do
 if env[‘HTTP_MY_KEY’] ==’rubyrocks‘
   error 401
 end
end
Demo
Stream
‣ Supports streamed content
‣ Streamed responses have no Content-
  Length header
‣ But have Transfer-Encoding: chunked
Inside
Inside
‣ Sinatra source code is on github:
    http://github.com/sinatra/sinatra
‣ Less than 2k lines of code
‣ Based on Rack
Application style


Classic application
         vs
Modular application
Classic App

  Single file
 Standalone
Modular Apps


         Multi file
Subclassing Sinatra::Base
  Distributed as library
The code
What happen when a request arrives?


get (‘/hello’) do { ‘hello world’ }
Where do get come from?
require "sinatra"
outer_self = self
get '/' do
 "outer self: #{outer_self}, inner self: #{self}"
end


 outer self: main, inner self: #<Sinatra::Application:

        closures in ruby are “scope gate”
$ irb
$ irb
ruby-1.9.2-p180 > require 'sinatra'
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
ruby-1.9.2-p180 > Sinatra::Delegator.target
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
ruby-1.9.2-p180 > Sinatra::Delegator.target
=> Sinatra::Application
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
ruby-1.9.2-p180 > Sinatra::Delegator.target
=> Sinatra::Application
ruby-1.9.2-p180 > Sinatra::Application.method(:get)
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
ruby-1.9.2-p180 > Sinatra::Delegator.target
=> Sinatra::Application
ruby-1.9.2-p180 > Sinatra::Application.method(:get)
=> #<Method:
Sinatra::Application(Sinatra::Base).get>
Where do get come from?
‣ get is defined twice:
  – Once in Sinatra::Delegator a mixin
    extending Object
  – Once in Sinatra::Application
‣ The Delegator implementation simply
  delegate to Application
‣ That’s why we have get/post/...
  methods on main
How the block is invoked?
‣ The route! method finds the correct
  route

def route_eval
 throw :halt, yield
end

‣ throw is used to go back to the invoker
In base.rb

‣ The invoker


def invoke
 res = catch(:halt) { yield }
 # .... other code...
end
It’s a kind of magic!
Sinatra has ended his set
    (crowd applauds)
Questions?
demos at:
http://github.com/emadb/
     webnetconf_demo
Please rate this session
Scan the code, go online, rate this session

More Related Content

What's hot

Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
흥배 최
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
흥배 최
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11
흥배 최
 

What's hot (20)

Rest in flask
Rest in flaskRest in flask
Rest in flask
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java Coleções
Java ColeçõesJava Coleções
Java Coleções
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
As modificações na Linguagem: Java 7 e Java 8
As modificações na Linguagem: Java 7 e Java 8As modificações na Linguagem: Java 7 e Java 8
As modificações na Linguagem: Java 7 e Java 8
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Discover GraphQL with Python, Graphene and Odoo
Discover GraphQL with Python, Graphene and OdooDiscover GraphQL with Python, Graphene and Odoo
Discover GraphQL with Python, Graphene and Odoo
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
SOLID principles in practice: the Clean Architecture
SOLID principles in practice: the Clean ArchitectureSOLID principles in practice: the Clean Architecture
SOLID principles in practice: the Clean Architecture
 
WebLogic authentication debugging
WebLogic authentication debuggingWebLogic authentication debugging
WebLogic authentication debugging
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Interfaces e polimorfismo
Interfaces e polimorfismoInterfaces e polimorfismo
Interfaces e polimorfismo
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 

Similar to Sinatra for REST services

Socket applications
Socket applicationsSocket applications
Socket applications
João Moura
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
yiditushe
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
guoqing75
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
som_nangia
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
wilburlo
 

Similar to Sinatra for REST services (20)

Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Service
 
infra-as-code
infra-as-codeinfra-as-code
infra-as-code
 
Socket applications
Socket applicationsSocket applications
Socket applications
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
PSGI/Plack OSDC.TW
PSGI/Plack OSDC.TWPSGI/Plack OSDC.TW
PSGI/Plack OSDC.TW
 
Swing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and SinatraSwing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and Sinatra
 
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
Rack
RackRack
Rack
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hope
 
Sprockets
SprocketsSprockets
Sprockets
 
Sinatra
SinatraSinatra
Sinatra
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 

More from Emanuele DelBono

More from Emanuele DelBono (13)

The simplest thing that could possibly work
The simplest thing that could possibly workThe simplest thing that could possibly work
The simplest thing that could possibly work
 
Una crescita armoniosa
Una crescita armoniosaUna crescita armoniosa
Una crescita armoniosa
 
A sip of Elixir
A sip of ElixirA sip of Elixir
A sip of Elixir
 
React.js in real world apps.
React.js in real world apps. React.js in real world apps.
React.js in real world apps.
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
From ActiveRecord to EventSourcing
From ActiveRecord to EventSourcingFrom ActiveRecord to EventSourcing
From ActiveRecord to EventSourcing
 
Ruby seen by a C# developer
Ruby seen by a C# developerRuby seen by a C# developer
Ruby seen by a C# developer
 
Ruby loves DDD
Ruby loves DDDRuby loves DDD
Ruby loves DDD
 
An introduction to knockout.js
An introduction to knockout.jsAn introduction to knockout.js
An introduction to knockout.js
 
Node azure
Node azureNode azure
Node azure
 
Da programmatore a CEO
Da programmatore a CEODa programmatore a CEO
Da programmatore a CEO
 
Test driving an MVVM App
Test driving an MVVM AppTest driving an MVVM App
Test driving an MVVM App
 
Mocking
MockingMocking
Mocking
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Sinatra for REST services

  • 1. REST with Sinatra Emanuele DelBono @emadb
  • 2. Thanks to the sponsors
  • 3. About me I’m a software developer in CodicePlastico. I write Web applications in C# with ASP.NET MVC. I’m a member of <WEBdeBS/> a local web community. ...and I’m a wannabe Ruby developer ;-)
  • 4. Agenda ‣ Philosophy. Sweet and easy. ‣ REST. Yet another boring introduction. ‣ Hello world. Show some magic. ‣ Features. Amazing! ‣ Inside. How it works? ‣ Q&A. ...and thanks.
  • 5. Sinatra as a REST server
  • 6. What is isn’t ‣ Sinatra is not -another MV* framework -a full framework like Rails -an ORM -a game project
  • 7. Sinatra is just a DSL written in ruby
  • 9. Hello world ~$ gem install sinatra ~$ vi app.rb
  • 10. Hello world ~$ gem install sinatra ~$ vi app.rb require 'sinatra' get '/' do 'hello world!' end
  • 11. Hello world ~$ gem install sinatra ~$ vi app.rb require 'sinatra' get '/' do 'hello world!' end ~$ ruby app.rb
  • 12.
  • 13. Is it really so easy? ‣ Yep! (special thanks to Ruby sweeties) - get is a just a method (more later) - the route is the parameter - the block is what should be executed - the block returns the result - the server is built in (based on Rack)
  • 14. Let’s go REST What? Yet another REST introduction?
  • 15.
  • 16. 5 REST principles ‣ Uniform Interface ‣ HATEAOS ‣ Stateless ‣ Cacheable ‣ Client-Server ‣ Layered System
  • 17. Sinatra and REST ‣ Sinatra supports - All HTTP verbs - Caching - Content types - Routes - ....and all you need to build a rest server
  • 18. Give a look at the
  • 19. Verbs ‣ Support for all verbs - Get, Post, Put, Delete, Head, Options, Patch ‣ They are just methods
  • 20. Routing ‣ No need of route files or route maps ‣ The verb method takes the route as parameter
  • 21. Routing get ( ‘/todos’ ) {...} get ( ‘/todo/:id’ ) {...} get ( ‘/*’ ) {...}
  • 22. Routing Conditions get '/foo', :agent => /Mozilla/(d.d)s w?/ do "You're using Mozilla version #{params[:agent][0]}" end get '/foo' do # Matches non-Mozilla browsers end
  • 23. Routing Custom set(:prob) { |v| condition { rand <= v } } get '/win_a_car', :prob => 0.1 do "You won!" end get '/win_a_car' {"Sorry, you lost."}
  • 24. Xml or Json ‣ You can set the content_type to whatever you need content_type :json content_type :xml
  • 25. Status codes ‣ Set the HTTP status code is status 200 status 403
  • 26. Http Headers ‣ You can add your own headers headers "X-My-Value" => "this is my header"
  • 28. Cache ‣ You can set your cache information using the headers method headers "Cache-Control" => "public, must-revalidate, max-age=3600", "Expires" => Time.at(Time.now.to_i + (60
  • 29. Cache ‣ Or better, you can use the expires expires 3600, :public
  • 31. Authentication ‣ Basic authentication support through Rack ‣ Key-based authentication
  • 32. Basic Authentication use Rack::Auth::Basic, "Private area" do |usr, pwd| [usr, pwd] == ['admin', 'admin'] end
  • 33. Token authentication before do if env[‘HTTP_MY_KEY’] ==’rubyrocks‘ error 401 end end
  • 34. Demo
  • 35. Stream ‣ Supports streamed content ‣ Streamed responses have no Content- Length header ‣ But have Transfer-Encoding: chunked
  • 37. Inside ‣ Sinatra source code is on github: http://github.com/sinatra/sinatra ‣ Less than 2k lines of code ‣ Based on Rack
  • 38. Application style Classic application vs Modular application
  • 39. Classic App Single file Standalone
  • 40. Modular Apps Multi file Subclassing Sinatra::Base Distributed as library
  • 41. The code What happen when a request arrives? get (‘/hello’) do { ‘hello world’ }
  • 42. Where do get come from? require "sinatra" outer_self = self get '/' do "outer self: #{outer_self}, inner self: #{self}" end outer self: main, inner self: #<Sinatra::Application: closures in ruby are “scope gate”
  • 43.
  • 44. $ irb
  • 45. $ irb ruby-1.9.2-p180 > require 'sinatra'
  • 46. $ irb ruby-1.9.2-p180 > require 'sinatra' => true
  • 47. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get)
  • 48. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get>
  • 49. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
  • 50. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=]
  • 51. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=] ruby-1.9.2-p180 > Sinatra::Delegator.target
  • 52. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=] ruby-1.9.2-p180 > Sinatra::Delegator.target => Sinatra::Application
  • 53. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=] ruby-1.9.2-p180 > Sinatra::Delegator.target => Sinatra::Application ruby-1.9.2-p180 > Sinatra::Application.method(:get)
  • 54. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=] ruby-1.9.2-p180 > Sinatra::Delegator.target => Sinatra::Application ruby-1.9.2-p180 > Sinatra::Application.method(:get) => #<Method: Sinatra::Application(Sinatra::Base).get>
  • 55. Where do get come from? ‣ get is defined twice: – Once in Sinatra::Delegator a mixin extending Object – Once in Sinatra::Application ‣ The Delegator implementation simply delegate to Application ‣ That’s why we have get/post/... methods on main
  • 56. How the block is invoked? ‣ The route! method finds the correct route def route_eval throw :halt, yield end ‣ throw is used to go back to the invoker
  • 57. In base.rb ‣ The invoker def invoke res = catch(:halt) { yield } # .... other code... end
  • 58. It’s a kind of magic!
  • 59. Sinatra has ended his set (crowd applauds)
  • 62. Please rate this session Scan the code, go online, rate this session

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n