SlideShare uma empresa Scribd logo
1 de 82
Baixar para ler offline
sinatra,
         rack &
         middleware

This is made “soon after” railsconf, so you’ll just have to deal with the railsconf references
sinatra,
         rack &
         middleware
        Ben Schwarz
        @benschwarz
        http://github.com/benschwarz

This is made “soon after” railsconf, so you’ll just have to deal with the railsconf references
sinatra
from the top
... is fucking sweet
DSL
Built on Rack
More on that later
Blake Mizerany
  @bmizerany
Ever wondered what Blake Mizerany
looks like at 8 am after a huge
fucking bender in “old” vegas?
Eyyeaahh.
So, that DSL
heres an example of the most simple sinatra application you could probably make. The ‘get’
referrers to the HTTP verb. You should probably recognise this from rails land. The next part
is the “route”, here I’m just mapping the index / root. “erb :index” will render index.erb,
sinatra also has haml support out of the box.
heres an example of the most simple sinatra application you could probably make. The ‘get’
referrers to the HTTP verb. You should probably recognise this from rails land. The next part
is the “route”, here I’m just mapping the index / root. “erb :index” will render index.erb,
sinatra also has haml support out of the box.
heres an example of the most simple sinatra application you could probably make. The ‘get’
referrers to the HTTP verb. You should probably recognise this from rails land. The next part
is the “route”, here I’m just mapping the index / root. “erb :index” will render index.erb,
sinatra also has haml support out of the box.
heres an example of the most simple sinatra application you could probably make. The ‘get’
referrers to the HTTP verb. You should probably recognise this from rails land. The next part
is the “route”, here I’m just mapping the index / root. “erb :index” will render index.erb,
sinatra also has haml support out of the box.
a ‘post’ example. you might notice the params hash is nothing new if you’ve come from rails
land.
a ‘post’ example. you might notice the params hash is nothing new if you’ve come from rails
land.
a ‘post’ example. you might notice the params hash is nothing new if you’ve come from rails
land.
a ‘post’ example. you might notice the params hash is nothing new if you’ve come from rails
land.
a slightly more advanced example. Here I create a mime type of :json and use before (read:
like before_filter) to set the :json content type before all routes. The .to_json method isn’t
Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord
of course has this built in.
a slightly more advanced example. Here I create a mime type of :json and use before (read:
like before_filter) to set the :json content type before all routes. The .to_json method isn’t
Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord
of course has this built in.
a slightly more advanced example. Here I create a mime type of :json and use before (read:
like before_filter) to set the :json content type before all routes. The .to_json method isn’t
Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord
of course has this built in.
a slightly more advanced example. Here I create a mime type of :json and use before (read:
like before_filter) to set the :json content type before all routes. The .to_json method isn’t
Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord
of course has this built in.
a slightly more advanced example. Here I create a mime type of :json and use before (read:
like before_filter) to set the :json content type before all routes. The .to_json method isn’t
Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord
of course has this built in.
a slightly more advanced example. Here I create a mime type of :json and use before (read:
like before_filter) to set the :json content type before all routes. The .to_json method isn’t
Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord
of course has this built in.
This is called “Classic”
        Sinatra application style




This means that the get and post (read: your application) is defined at the top level
Apps can also be defined in another way.
Modular apps are defined within their own namespace / class.
They inherit from Sinatra::Base
Apps can also be defined in another way.
Modular apps are defined within their own namespace / class.
They inherit from Sinatra::Base
Thats a “Modular”
         Sinatra application




I’ll get into modular apps a little more later
Running it


So by now, if you’re unfamiliar with rack or sinatra you’ll might be thinking, “but we just got
passenger, ruby hosting has only now become ‘easy’”
Development
you could use the `rackup` command, but instead you should use ‘shotgun’ by Ryan
Tomayko, it handles application reloading (which is not present within the sinatra codebase)
Ryan Tomayko
  @rtomayko
Ever wondered what Ryan Tomayko
looks like at 8 am after a huge
fucking bender in “old” vegas?
Not much earlier (5am) Ryan sent his wife an email saying “Melbourne, we’re going”. She
called in the morning to find out if he was mid-way across the pacific or not.
Production
Drop in a config.ru to
        your application root




config.Rack-Up, rack uses this to load and configure rack applications and middleware
this is a simple config.ru file. its for a ‘classic’ application
For those “Modular”
applications
a rackup file (config.ru) example for a modular application
Then drop it under
        passenger. Done




Of course you’ll need to read some docs, but its so trivial its not even worth mentioning
Heres the part where I
        hock my own warez




Just some assorted things that I have found really fun or interesting in the last few months
Amnesia
Statistics for memcached instances
So thats all your hits, misses and basic stats to tell you what the hell your memcached
instances are doing. If they’re getting smashed. Etc. I know iseekgolf, a large australian
golfing website have used it, along with some engineyard customers. github and flickr also
checked it out which was pretty cool. Amnesia was a 2 session application, one for
implementation, the next to add the graphs etc. I think I spent about 5 hours total on it.
Munch
         Recipes from websites re-represented




I showed this last month, its pretty simple so I’ll gloss over it.
Basically a aggregate search engine for cooking sites
Postie



Postie was originally a rails app, ported to merb
Pat Allan
                       @pat




Pat allan wrote it
Postie
        A Rack middleware to provide postcode services




I decided to make the next natural progression and re-write it as a rack middleware
It has its own datamapper based sqlite backend. When a new build comes out, new data will
be installed along with the gem. Its quite small though.
Here is the basic api
Here is the basic api
Here is the basic api
Hold on, rack
         middleware?




If you thought we were talking about sinatra, well, you’re right.
So how does that work?
Sinatra runs on Rack
Sinatra (wolf)
        Rack (sheeps clothing)




This is a strange analogy. I don’t know.
So when you go and define you app in “modular style”, it can be used as a rack middleware.
a config.ru file to run your application as middleware, note the use of “use”.
a config.ru file to run your application as middleware, note the use of “use”.
a config.ru file to run your application as middleware, note the use of “use”.
In rails land, you do it like this
In rails land, you do it like this
In rails land, you do it like this
In rails land, you do it like this
Selected
middlewares
Rack::Cache
and again, its made by Ryan Tomayko
Reverse proxy
         Like Squid or Varnish, but small and simple




It’ll set correct http headers. Thats really important. The main basis of this is that your
application pages can be cached by rack::cache and stop requests from even having to hit
your ruby process.
JSON-P



Json-p is for when you want to get callbacks for your json / ajax requests from your server.
The data will be returned wrapped within a callback method. This can make writing a
javascript based interface much faster and easier to implement.
instead of doing something like this
you can add a callback parameter
so instead of getting some result like we did earlier, a raw javascript / json “string” in the
browser that needs to be eval’d and looked after
you can get it back like this, it calls your method and can be handled more cleanly
JSON-P
        part of rack-contrib




Json-p is for when you want to get callbacks for your json / ajax requests from your server.
The data will be returned wrapped within a callback method. This can make writing a
javascript based interface much faster and easier to implement.
Hancock



The last one I’ll show is “hancock”
A REAL implementation
        of single-sign-on




Engine yard are using this internally and I really suggest that you read the code. There are
some videos available online and it stands as the best example of sinatra based rack
middleware. Hancock was the only real implementation of a sinatra based rack middleware
that he sinatra committers could point me at. I used it as a basis for learning how to pack
postie together.
Thanks

Special Thanks to Blake and Ryan for being good sports.
Thanks
                     http://sinatrarb.com
                     http://twitter.com/bmizerany
                     http://twitter.com/rtomayko
                     http://github.com/benschwarz/amnesia
                     http://github.com/benschwarz/munch
                     http://github.com/benschwarz/postie
                     http://github.com/rtomayko/shotgun
                     http://github.com/rack/rack-contrib
                     http://github.com/atmos/hancock/tree/master
                     http://github.com/atmos/hancock-client/tree/master
                     http://en.wikipedia.org/wiki/Single_sign-on




Special Thanks to Blake and Ryan for being good sports.

Mais conteúdo relacionado

Mais procurados

Tips Rastreo e Indexación en Proyectos Reales [Congreso Web Zaragoza 2018]
Tips Rastreo e Indexación en Proyectos Reales [Congreso Web Zaragoza 2018]Tips Rastreo e Indexación en Proyectos Reales [Congreso Web Zaragoza 2018]
Tips Rastreo e Indexación en Proyectos Reales [Congreso Web Zaragoza 2018]Luis M Villanueva
 
NY WebPerf Sept '22 - Performance Mistakes - An HTTP Archive Deep Dive
NY WebPerf Sept '22 - Performance Mistakes - An HTTP Archive Deep DiveNY WebPerf Sept '22 - Performance Mistakes - An HTTP Archive Deep Dive
NY WebPerf Sept '22 - Performance Mistakes - An HTTP Archive Deep DivePaul Calvano
 
Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018Darío Kondratiuk
 
간단한 블로그를 만들며 Django 이해하기
간단한 블로그를 만들며 Django 이해하기간단한 블로그를 만들며 Django 이해하기
간단한 블로그를 만들며 Django 이해하기Kyoung Up Jung
 
Spring bootでweb バリデート編
Spring bootでweb バリデート編Spring bootでweb バリデート編
Spring bootでweb バリデート編なべ
 
Spring Bootをはじめる時にやるべき10のこと
Spring Bootをはじめる時にやるべき10のことSpring Bootをはじめる時にやるべき10のこと
Spring Bootをはじめる時にやるべき10のこと心 谷本
 
Basic of HTML, CSS(StyleSheet), JavaScript(js), Bootstrap, JSON & AngularJS
Basic of HTML, CSS(StyleSheet), JavaScript(js), Bootstrap, JSON & AngularJSBasic of HTML, CSS(StyleSheet), JavaScript(js), Bootstrap, JSON & AngularJS
Basic of HTML, CSS(StyleSheet), JavaScript(js), Bootstrap, JSON & AngularJSDeepak Upadhyay
 
The State of Pagination & Infinite Scroll - BrightonSEO April 2019 - Adam Gent
The State of Pagination & Infinite Scroll - BrightonSEO   April 2019 - Adam GentThe State of Pagination & Infinite Scroll - BrightonSEO   April 2019 - Adam Gent
The State of Pagination & Infinite Scroll - BrightonSEO April 2019 - Adam GentDeepCrawl
 
Massive service basic
Massive service basicMassive service basic
Massive service basicDaeMyung Kang
 
The intersection between SEO and accessibility.pdf
The intersection between SEO and accessibility.pdfThe intersection between SEO and accessibility.pdf
The intersection between SEO and accessibility.pdfJessMackereth
 
게임 서비스 품질 향상을 위한 데이터 분석 활용하기 - 김필중 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
게임 서비스 품질 향상을 위한 데이터 분석 활용하기 - 김필중 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming게임 서비스 품질 향상을 위한 데이터 분석 활용하기 - 김필중 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
게임 서비스 품질 향상을 위한 데이터 분석 활용하기 - 김필중 솔루션즈 아키텍트:: AWS Cloud Track 3 GamingAmazon Web Services Korea
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
與 Sign in with Apple 的愛恨情仇 @ iPlayground2020
與 Sign in with Apple 的愛恨情仇 @ iPlayground2020與 Sign in with Apple 的愛恨情仇 @ iPlayground2020
與 Sign in with Apple 的愛恨情仇 @ iPlayground2020Johnny Sung
 
Java + React.jsでSever Side Rendering #reactjs_meetup
Java + React.jsでSever Side Rendering #reactjs_meetupJava + React.jsでSever Side Rendering #reactjs_meetup
Java + React.jsでSever Side Rendering #reactjs_meetupToshiaki Maki
 
HTML presentation for beginners
HTML presentation for beginnersHTML presentation for beginners
HTML presentation for beginnersjeroenvdmeer
 
Django in Production
Django in ProductionDjango in Production
Django in ProductionHyun-woo Park
 
인프런 - 스타트업 인프랩 시작 사례
인프런 - 스타트업 인프랩 시작 사례인프런 - 스타트업 인프랩 시작 사례
인프런 - 스타트업 인프랩 시작 사례Hyung Lee
 

Mais procurados (20)

Tips Rastreo e Indexación en Proyectos Reales [Congreso Web Zaragoza 2018]
Tips Rastreo e Indexación en Proyectos Reales [Congreso Web Zaragoza 2018]Tips Rastreo e Indexación en Proyectos Reales [Congreso Web Zaragoza 2018]
Tips Rastreo e Indexación en Proyectos Reales [Congreso Web Zaragoza 2018]
 
NY WebPerf Sept '22 - Performance Mistakes - An HTTP Archive Deep Dive
NY WebPerf Sept '22 - Performance Mistakes - An HTTP Archive Deep DiveNY WebPerf Sept '22 - Performance Mistakes - An HTTP Archive Deep Dive
NY WebPerf Sept '22 - Performance Mistakes - An HTTP Archive Deep Dive
 
Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018
 
간단한 블로그를 만들며 Django 이해하기
간단한 블로그를 만들며 Django 이해하기간단한 블로그를 만들며 Django 이해하기
간단한 블로그를 만들며 Django 이해하기
 
Spring bootでweb バリデート編
Spring bootでweb バリデート編Spring bootでweb バリデート編
Spring bootでweb バリデート編
 
Spring Bootをはじめる時にやるべき10のこと
Spring Bootをはじめる時にやるべき10のことSpring Bootをはじめる時にやるべき10のこと
Spring Bootをはじめる時にやるべき10のこと
 
Basic of HTML, CSS(StyleSheet), JavaScript(js), Bootstrap, JSON & AngularJS
Basic of HTML, CSS(StyleSheet), JavaScript(js), Bootstrap, JSON & AngularJSBasic of HTML, CSS(StyleSheet), JavaScript(js), Bootstrap, JSON & AngularJS
Basic of HTML, CSS(StyleSheet), JavaScript(js), Bootstrap, JSON & AngularJS
 
The State of Pagination & Infinite Scroll - BrightonSEO April 2019 - Adam Gent
The State of Pagination & Infinite Scroll - BrightonSEO   April 2019 - Adam GentThe State of Pagination & Infinite Scroll - BrightonSEO   April 2019 - Adam Gent
The State of Pagination & Infinite Scroll - BrightonSEO April 2019 - Adam Gent
 
Massive service basic
Massive service basicMassive service basic
Massive service basic
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
The intersection between SEO and accessibility.pdf
The intersection between SEO and accessibility.pdfThe intersection between SEO and accessibility.pdf
The intersection between SEO and accessibility.pdf
 
게임 서비스 품질 향상을 위한 데이터 분석 활용하기 - 김필중 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
게임 서비스 품질 향상을 위한 데이터 분석 활용하기 - 김필중 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming게임 서비스 품질 향상을 위한 데이터 분석 활용하기 - 김필중 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
게임 서비스 품질 향상을 위한 데이터 분석 활용하기 - 김필중 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
與 Sign in with Apple 的愛恨情仇 @ iPlayground2020
與 Sign in with Apple 的愛恨情仇 @ iPlayground2020與 Sign in with Apple 的愛恨情仇 @ iPlayground2020
與 Sign in with Apple 的愛恨情仇 @ iPlayground2020
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Java + React.jsでSever Side Rendering #reactjs_meetup
Java + React.jsでSever Side Rendering #reactjs_meetupJava + React.jsでSever Side Rendering #reactjs_meetup
Java + React.jsでSever Side Rendering #reactjs_meetup
 
HTML presentation for beginners
HTML presentation for beginnersHTML presentation for beginners
HTML presentation for beginners
 
How Browsers Work
How Browsers Work How Browsers Work
How Browsers Work
 
Django in Production
Django in ProductionDjango in Production
Django in Production
 
인프런 - 스타트업 인프랩 시작 사례
인프런 - 스타트업 인프랩 시작 사례인프런 - 스타트업 인프랩 시작 사례
인프런 - 스타트업 인프랩 시작 사례
 

Destaque

Rails vs Django Study Presentation
Rails vs Django Study PresentationRails vs Django Study Presentation
Rails vs Django Study PresentationMongol Mix Project
 
ICT4S - Designing for Sustainability: Breakthrough or suboptimisation
ICT4S - Designing for Sustainability: Breakthrough or suboptimisationICT4S - Designing for Sustainability: Breakthrough or suboptimisation
ICT4S - Designing for Sustainability: Breakthrough or suboptimisationSURFsara
 
ICT4S - The energy and carbon footprint of the ICT and E&M sector in Sweden 1...
ICT4S - The energy and carbon footprint of the ICT and E&M sector in Sweden 1...ICT4S - The energy and carbon footprint of the ICT and E&M sector in Sweden 1...
ICT4S - The energy and carbon footprint of the ICT and E&M sector in Sweden 1...SURFsara
 
ICT4S keynote - Frances Brazier
ICT4S keynote - Frances BrazierICT4S keynote - Frances Brazier
ICT4S keynote - Frances BrazierSURFsara
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with RubyAnis Ahmad
 

Destaque (6)

Sinatra
SinatraSinatra
Sinatra
 
Rails vs Django Study Presentation
Rails vs Django Study PresentationRails vs Django Study Presentation
Rails vs Django Study Presentation
 
ICT4S - Designing for Sustainability: Breakthrough or suboptimisation
ICT4S - Designing for Sustainability: Breakthrough or suboptimisationICT4S - Designing for Sustainability: Breakthrough or suboptimisation
ICT4S - Designing for Sustainability: Breakthrough or suboptimisation
 
ICT4S - The energy and carbon footprint of the ICT and E&M sector in Sweden 1...
ICT4S - The energy and carbon footprint of the ICT and E&M sector in Sweden 1...ICT4S - The energy and carbon footprint of the ICT and E&M sector in Sweden 1...
ICT4S - The energy and carbon footprint of the ICT and E&M sector in Sweden 1...
 
ICT4S keynote - Frances Brazier
ICT4S keynote - Frances BrazierICT4S keynote - Frances Brazier
ICT4S keynote - Frances Brazier
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 

Semelhante a Sinatra Rack And Middleware

Rapid API Development with LoopBack/StrongLoop
Rapid API Development with LoopBack/StrongLoopRapid API Development with LoopBack/StrongLoop
Rapid API Development with LoopBack/StrongLoopRaymond Camden
 
Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Servicevvatikiotis
 
DiUS Computing Lca Rails Final
DiUS  Computing Lca Rails FinalDiUS  Computing Lca Rails Final
DiUS Computing Lca Rails FinalRobert Postill
 
Web Hooks and the Programmable World of Tomorrow
Web Hooks and the Programmable World of TomorrowWeb Hooks and the Programmable World of Tomorrow
Web Hooks and the Programmable World of TomorrowJeff Lindsay
 
Synchronous Reads Asynchronous Writes RubyConf 2009
Synchronous Reads Asynchronous Writes RubyConf 2009Synchronous Reads Asynchronous Writes RubyConf 2009
Synchronous Reads Asynchronous Writes RubyConf 2009pauldix
 
Finding Frank - Spotify API.pdf
Finding Frank - Spotify API.pdfFinding Frank - Spotify API.pdf
Finding Frank - Spotify API.pdfaspleenic
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011Lance Ball
 
OSDC 2018 - Distributed monitoring
OSDC 2018 - Distributed monitoringOSDC 2018 - Distributed monitoring
OSDC 2018 - Distributed monitoringGianluca Arbezzano
 
OSDC 2018 | Distributed Monitoring by Gianluca Arbezzano
OSDC 2018 | Distributed Monitoring by Gianluca ArbezzanoOSDC 2018 | Distributed Monitoring by Gianluca Arbezzano
OSDC 2018 | Distributed Monitoring by Gianluca ArbezzanoNETWAYS
 
Writing a REST Interconnection Library in Swift
Writing a REST Interconnection Library in SwiftWriting a REST Interconnection Library in Swift
Writing a REST Interconnection Library in SwiftPablo Villar
 
Offline of web applications
Offline of web applicationsOffline of web applications
Offline of web applicationsFDConf
 
Offline for web - Frontend Dev Conf Minsk 2014
Offline for web - Frontend Dev Conf Minsk 2014Offline for web - Frontend Dev Conf Minsk 2014
Offline for web - Frontend Dev Conf Minsk 2014Jan Jongboom
 
Socket applications
Socket applicationsSocket applications
Socket applicationsJoão Moura
 
Ambiguous Sinatra - Vadim Evseev
Ambiguous Sinatra - Vadim EvseevAmbiguous Sinatra - Vadim Evseev
Ambiguous Sinatra - Vadim EvseevRuby Meditation
 
Ambiguous Sinatra
Ambiguous SinatraAmbiguous Sinatra
Ambiguous SinatraAmoniac OÜ
 
Solving the Riddle of Search: Using Sphinx with Rails
Solving the Riddle of Search: Using Sphinx with RailsSolving the Riddle of Search: Using Sphinx with Rails
Solving the Riddle of Search: Using Sphinx with Railsfreelancing_god
 

Semelhante a Sinatra Rack And Middleware (20)

Introduce Django
Introduce DjangoIntroduce Django
Introduce Django
 
Rapid API Development with LoopBack/StrongLoop
Rapid API Development with LoopBack/StrongLoopRapid API Development with LoopBack/StrongLoop
Rapid API Development with LoopBack/StrongLoop
 
Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Service
 
DiUS Computing Lca Rails Final
DiUS  Computing Lca Rails FinalDiUS  Computing Lca Rails Final
DiUS Computing Lca Rails Final
 
Web Hooks and the Programmable World of Tomorrow
Web Hooks and the Programmable World of TomorrowWeb Hooks and the Programmable World of Tomorrow
Web Hooks and the Programmable World of Tomorrow
 
Synchronous Reads Asynchronous Writes RubyConf 2009
Synchronous Reads Asynchronous Writes RubyConf 2009Synchronous Reads Asynchronous Writes RubyConf 2009
Synchronous Reads Asynchronous Writes RubyConf 2009
 
Automate Yo' Self
Automate Yo' SelfAutomate Yo' Self
Automate Yo' Self
 
Finding Frank - Spotify API.pdf
Finding Frank - Spotify API.pdfFinding Frank - Spotify API.pdf
Finding Frank - Spotify API.pdf
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
Railties
RailtiesRailties
Railties
 
OSDC 2018 - Distributed monitoring
OSDC 2018 - Distributed monitoringOSDC 2018 - Distributed monitoring
OSDC 2018 - Distributed monitoring
 
OSDC 2018 | Distributed Monitoring by Gianluca Arbezzano
OSDC 2018 | Distributed Monitoring by Gianluca ArbezzanoOSDC 2018 | Distributed Monitoring by Gianluca Arbezzano
OSDC 2018 | Distributed Monitoring by Gianluca Arbezzano
 
zas-agent-0.1.1
zas-agent-0.1.1zas-agent-0.1.1
zas-agent-0.1.1
 
Writing a REST Interconnection Library in Swift
Writing a REST Interconnection Library in SwiftWriting a REST Interconnection Library in Swift
Writing a REST Interconnection Library in Swift
 
Offline of web applications
Offline of web applicationsOffline of web applications
Offline of web applications
 
Offline for web - Frontend Dev Conf Minsk 2014
Offline for web - Frontend Dev Conf Minsk 2014Offline for web - Frontend Dev Conf Minsk 2014
Offline for web - Frontend Dev Conf Minsk 2014
 
Socket applications
Socket applicationsSocket applications
Socket applications
 
Ambiguous Sinatra - Vadim Evseev
Ambiguous Sinatra - Vadim EvseevAmbiguous Sinatra - Vadim Evseev
Ambiguous Sinatra - Vadim Evseev
 
Ambiguous Sinatra
Ambiguous SinatraAmbiguous Sinatra
Ambiguous Sinatra
 
Solving the Riddle of Search: Using Sphinx with Rails
Solving the Riddle of Search: Using Sphinx with RailsSolving the Riddle of Search: Using Sphinx with Rails
Solving the Riddle of Search: Using Sphinx with Rails
 

Último

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Último (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

Sinatra Rack And Middleware

  • 1. sinatra, rack & middleware This is made “soon after” railsconf, so you’ll just have to deal with the railsconf references
  • 2. sinatra, rack & middleware Ben Schwarz @benschwarz http://github.com/benschwarz This is made “soon after” railsconf, so you’ll just have to deal with the railsconf references
  • 6. DSL
  • 7. Built on Rack More on that later
  • 8. Blake Mizerany @bmizerany
  • 9. Ever wondered what Blake Mizerany looks like at 8 am after a huge fucking bender in “old” vegas?
  • 10.
  • 13. heres an example of the most simple sinatra application you could probably make. The ‘get’ referrers to the HTTP verb. You should probably recognise this from rails land. The next part is the “route”, here I’m just mapping the index / root. “erb :index” will render index.erb, sinatra also has haml support out of the box.
  • 14. heres an example of the most simple sinatra application you could probably make. The ‘get’ referrers to the HTTP verb. You should probably recognise this from rails land. The next part is the “route”, here I’m just mapping the index / root. “erb :index” will render index.erb, sinatra also has haml support out of the box.
  • 15. heres an example of the most simple sinatra application you could probably make. The ‘get’ referrers to the HTTP verb. You should probably recognise this from rails land. The next part is the “route”, here I’m just mapping the index / root. “erb :index” will render index.erb, sinatra also has haml support out of the box.
  • 16. heres an example of the most simple sinatra application you could probably make. The ‘get’ referrers to the HTTP verb. You should probably recognise this from rails land. The next part is the “route”, here I’m just mapping the index / root. “erb :index” will render index.erb, sinatra also has haml support out of the box.
  • 17. a ‘post’ example. you might notice the params hash is nothing new if you’ve come from rails land.
  • 18. a ‘post’ example. you might notice the params hash is nothing new if you’ve come from rails land.
  • 19. a ‘post’ example. you might notice the params hash is nothing new if you’ve come from rails land.
  • 20. a ‘post’ example. you might notice the params hash is nothing new if you’ve come from rails land.
  • 21. a slightly more advanced example. Here I create a mime type of :json and use before (read: like before_filter) to set the :json content type before all routes. The .to_json method isn’t Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord of course has this built in.
  • 22. a slightly more advanced example. Here I create a mime type of :json and use before (read: like before_filter) to set the :json content type before all routes. The .to_json method isn’t Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord of course has this built in.
  • 23. a slightly more advanced example. Here I create a mime type of :json and use before (read: like before_filter) to set the :json content type before all routes. The .to_json method isn’t Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord of course has this built in.
  • 24. a slightly more advanced example. Here I create a mime type of :json and use before (read: like before_filter) to set the :json content type before all routes. The .to_json method isn’t Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord of course has this built in.
  • 25. a slightly more advanced example. Here I create a mime type of :json and use before (read: like before_filter) to set the :json content type before all routes. The .to_json method isn’t Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord of course has this built in.
  • 26. a slightly more advanced example. Here I create a mime type of :json and use before (read: like before_filter) to set the :json content type before all routes. The .to_json method isn’t Sinatra magic. In this case it comes from using datamappers’ aggrigates plugin, activerecord of course has this built in.
  • 27. This is called “Classic” Sinatra application style This means that the get and post (read: your application) is defined at the top level
  • 28. Apps can also be defined in another way. Modular apps are defined within their own namespace / class. They inherit from Sinatra::Base
  • 29. Apps can also be defined in another way. Modular apps are defined within their own namespace / class. They inherit from Sinatra::Base
  • 30. Thats a “Modular” Sinatra application I’ll get into modular apps a little more later
  • 31. Running it So by now, if you’re unfamiliar with rack or sinatra you’ll might be thinking, “but we just got passenger, ruby hosting has only now become ‘easy’”
  • 33. you could use the `rackup` command, but instead you should use ‘shotgun’ by Ryan Tomayko, it handles application reloading (which is not present within the sinatra codebase)
  • 34. Ryan Tomayko @rtomayko
  • 35. Ever wondered what Ryan Tomayko looks like at 8 am after a huge fucking bender in “old” vegas?
  • 36. Not much earlier (5am) Ryan sent his wife an email saying “Melbourne, we’re going”. She called in the morning to find out if he was mid-way across the pacific or not.
  • 38. Drop in a config.ru to your application root config.Rack-Up, rack uses this to load and configure rack applications and middleware
  • 39. this is a simple config.ru file. its for a ‘classic’ application
  • 41. a rackup file (config.ru) example for a modular application
  • 42. Then drop it under passenger. Done Of course you’ll need to read some docs, but its so trivial its not even worth mentioning
  • 43. Heres the part where I hock my own warez Just some assorted things that I have found really fun or interesting in the last few months
  • 45. So thats all your hits, misses and basic stats to tell you what the hell your memcached instances are doing. If they’re getting smashed. Etc. I know iseekgolf, a large australian golfing website have used it, along with some engineyard customers. github and flickr also checked it out which was pretty cool. Amnesia was a 2 session application, one for implementation, the next to add the graphs etc. I think I spent about 5 hours total on it.
  • 46. Munch Recipes from websites re-represented I showed this last month, its pretty simple so I’ll gloss over it.
  • 47. Basically a aggregate search engine for cooking sites
  • 48. Postie Postie was originally a rails app, ported to merb
  • 49. Pat Allan @pat Pat allan wrote it
  • 50. Postie A Rack middleware to provide postcode services I decided to make the next natural progression and re-write it as a rack middleware
  • 51. It has its own datamapper based sqlite backend. When a new build comes out, new data will be installed along with the gem. Its quite small though.
  • 52. Here is the basic api
  • 53. Here is the basic api
  • 54. Here is the basic api
  • 55.
  • 56.
  • 57. Hold on, rack middleware? If you thought we were talking about sinatra, well, you’re right.
  • 58. So how does that work?
  • 60. Sinatra (wolf) Rack (sheeps clothing) This is a strange analogy. I don’t know.
  • 61. So when you go and define you app in “modular style”, it can be used as a rack middleware.
  • 62. a config.ru file to run your application as middleware, note the use of “use”.
  • 63. a config.ru file to run your application as middleware, note the use of “use”.
  • 64. a config.ru file to run your application as middleware, note the use of “use”.
  • 65. In rails land, you do it like this
  • 66. In rails land, you do it like this
  • 67. In rails land, you do it like this
  • 68. In rails land, you do it like this
  • 71. and again, its made by Ryan Tomayko
  • 72. Reverse proxy Like Squid or Varnish, but small and simple It’ll set correct http headers. Thats really important. The main basis of this is that your application pages can be cached by rack::cache and stop requests from even having to hit your ruby process.
  • 73. JSON-P Json-p is for when you want to get callbacks for your json / ajax requests from your server. The data will be returned wrapped within a callback method. This can make writing a javascript based interface much faster and easier to implement.
  • 74. instead of doing something like this
  • 75. you can add a callback parameter
  • 76. so instead of getting some result like we did earlier, a raw javascript / json “string” in the browser that needs to be eval’d and looked after
  • 77. you can get it back like this, it calls your method and can be handled more cleanly
  • 78. JSON-P part of rack-contrib Json-p is for when you want to get callbacks for your json / ajax requests from your server. The data will be returned wrapped within a callback method. This can make writing a javascript based interface much faster and easier to implement.
  • 79. Hancock The last one I’ll show is “hancock”
  • 80. A REAL implementation of single-sign-on Engine yard are using this internally and I really suggest that you read the code. There are some videos available online and it stands as the best example of sinatra based rack middleware. Hancock was the only real implementation of a sinatra based rack middleware that he sinatra committers could point me at. I used it as a basis for learning how to pack postie together.
  • 81. Thanks Special Thanks to Blake and Ryan for being good sports.
  • 82. Thanks http://sinatrarb.com http://twitter.com/bmizerany http://twitter.com/rtomayko http://github.com/benschwarz/amnesia http://github.com/benschwarz/munch http://github.com/benschwarz/postie http://github.com/rtomayko/shotgun http://github.com/rack/rack-contrib http://github.com/atmos/hancock/tree/master http://github.com/atmos/hancock-client/tree/master http://en.wikipedia.org/wiki/Single_sign-on Special Thanks to Blake and Ryan for being good sports.