SlideShare a Scribd company logo
Sinatra: a Micro-framework for Web Applicationshttp://www.sinatrarb.com/Kevin ReissOffice of Library Services
What is Sinatra?A web application micro-frameworkMinimal stack frameworkA ruby Domain Specific Language (DSL)A ruby “rack” applicationA ruby “gem”Gems are the ruby equivalent ofPerl modulesPHP PEARManaging gems is very easy- Gem install sinatra is all you need
Why Sinatra?It is lightweightBuilt on the rack “gem”Rack is a generic ruby library for building web applicationsIt is nicely pluggable within other applicationsRails3 has featured support for sinatra apps as middlewareGood tool for creating REST-like interfaces Supports many different template syntaxesIt has it’s own web server: default thinConvention over Configuration: the Ruby Framework Way
Hello World?# hello_world.rbrequire 'sinatra' # a single sinatra block with a return valueget '/' do   'Hello world!'  # return the string “Hello World”endTo run the app:> ruby hellow_world.rb
Second Hello World AppSinatra configurationSinatra routesSinatra helpersWatch your Request values
Sinatra: Helpers, Routes, and Blockshelpers do  def format_title(name)name.capitalize # your return value  endEndget '/library/:department' do  @title = "#{format_title(params[:department])} Department".striphaml :department # invoke a templateend
Views with SinatraStandard conventionViews always go in the “views” directoryTemplates marked “layout.ext” are automatically used as wrappers for “content-like templates” like “mycustomdisplay.ext”Static files (stylesheets, images, etc.) are served up out of the “public” directorySupport a wide variety of template options to generate XHTML, HTML5, XML, etc. Can easily define custom formatsIntegration with RACK makes it easy to deal with the parts of an HTTP Request
HAML TemplatesHAML – HTML Templates for the LazyAlso bundled with a CSS Template: SASS%html{:"xml:lang"=>"en"}  %head    %title My Library Web: #{@title}    %link{:type=>"text/css",:rel=>"stylesheet",:media=>"screen",:href=>"/stylesheet.css"}  %body    #pageContent      #header        %ul.nav          %li            %a{:href=>"/"} Home      #body        =yield      #footer        %p Office of Library Services
Where is the Registry?Set configuration options and constants easilySinatra’s integration with rack makes it easy to access and manipulate the contents of the http.request associated
What about Testing?Unit tests are built into rackset :environment, :testclass LibraryTest < Test::Unit::TestCase  def test_it_says_hello_world    browser = Rack::Test::Session.new(Rack::MockSession.new(Sinatra::Application))browser.get '/'    assert browser.last_response.ok?assert_equal '<h1>Hello World!</h1>', browser.last_response.body  end  def test_it_says_hello_to_a_department    browser = Rack::Test::Session.new(Rack::MockSession.new(Sinatra::Application))browser.get '/library/ill'    assert browser.last_response.body.include?('ill')  endend
Deployment OptionsLaunch Locally with ruby thin web serverThis is built into the applicationPublish directly to herokuLaunch via apacheproxy_balancer modulepassenger modulengnix
Heroku FeaturesRead-only filesystemInstalled as a ruby gemIntegrated with git and sshFree for low-volume applicationsAdd-ons to expand functionalityMemcacheDatabases,DNS, heroku logsGood documentationNot just sinatra, rails and any other rack-based applicationSimilar to the “Google App Engine”
Heroku Deployment	Ruby Platform as a Service – http://heroku.com/Rails, Sinatra, generic Rack ApplicationsIntegrated directly with git version to controlTo Deploy:create “config.ru” file – defines your rack applicationcreate .gems file – defines libraries your app requiresgit initgit add .git commit –m “Initial Commit”heroku creategit push heroku master
Thin Server Configuration--- chdir: /home/kreiss/ruby/lookup/rackup: /home/kreiss/ruby/lookup/config.ruenvironment: productionaddress: 127.0.0.1port: 5000timeout: 30log: /home/kreiss/ruby/lookup/log/thin.logpid: /home/kreiss/ruby/lookup/tmp/pids/thin.pidmax_conns: 1024max_persistent_conns: 512require: []wait: 30servers: 3daemonize: true
An Actual ApplicationStandard number checkerWrapper for our web services provided by our ILSEmbed this as a web service in other application/scripts
REST-Like InterfaceOutput multiple formatsJSONCustom XML with builder gemXML parsing handled by the nokogiri ruby gem
More Complicated Sample Routeget '/:campus/isbn/:isbn' dolookup_base = is_valid_sublibrary(params[:campus])  @number = is_valid_isbn(params[:isbn])  @type = "ISBN"  @title = “#{@type}: #{@number} for campus #{lookup_base}"  @items = standard_lookup(@number, "bath.isbn", lookup_base)  if params[:format] == "xml"    builder :bibelsifparams[:format] == "json"    @items.to_json  elsehaml :standard  endend
Heroku Deployment486  curl http://cunylookup.heroku.com/laguardia/barcode/33324001754295487  curl http://cunylookup.heroku.com/city/isbn/0800630807488  curl http://cunylookup.heroku.com/city/isbn/0800630807?format=xml489  curl http://cunylookup.heroku.com/city/isbn/0800630807?format=json490  curl http://cunylookup.heroku.com/cun01/isbn/0800630807491  curl http://cunylookup.heroku.com/cun01/isbn/0800630807?format=json492  curl http://cunylookup.heroku.com/cun01/isbn/0800630807?format=xml493  curl http://cunylookup.heroku.com/cun01/isbn/0800630807?format=xml494  curl http://cunylookup.heroku.com/cun01/issn/1092-7735?format=xml495  curl http://cunylookup.heroku.com/city/issn/1092-7735?format=xml496  curl http://cunylookup.heroku.com/laguardia/issn/1092-7735?format=xml497  curl http://cunylookup.heroku.com/laguardia/lccn/96042502?format=xml498  curl http://cunylookup.heroku.com/cun01/lccn/96042502?format=xml
GotchasRuby 1.8 v. Ruby 1.9Heroku supports bothGems need to be called differently in ruby 1.8Name your gems sensibly – annoying rubyismDalli: name for memcache gemNokogiri: name for xml processing gemSinatra vs. Sinatra BaseIf you plan to use as middleware in another ruby app you need to define your application with sinatra base
Other frameworks in LibrariesRails (Blacklight)PHP Zend (Omeka)Django (Solr front-end)Xerxes (Metasearch)
Drupal Platform	ServicesViews datasourceDrupal Workflow building capabilitiesWorkflow moduleNew workbench toolkitD7 Rest Server
Code4lib ReportLooks of repository middleware
Code4libNYC	Suggestion to host day long event

More Related Content

Sinatra

  • 1. Sinatra: a Micro-framework for Web Applicationshttp://www.sinatrarb.com/Kevin ReissOffice of Library Services
  • 2. What is Sinatra?A web application micro-frameworkMinimal stack frameworkA ruby Domain Specific Language (DSL)A ruby “rack” applicationA ruby “gem”Gems are the ruby equivalent ofPerl modulesPHP PEARManaging gems is very easy- Gem install sinatra is all you need
  • 3. Why Sinatra?It is lightweightBuilt on the rack “gem”Rack is a generic ruby library for building web applicationsIt is nicely pluggable within other applicationsRails3 has featured support for sinatra apps as middlewareGood tool for creating REST-like interfaces Supports many different template syntaxesIt has it’s own web server: default thinConvention over Configuration: the Ruby Framework Way
  • 4. Hello World?# hello_world.rbrequire 'sinatra' # a single sinatra block with a return valueget '/' do 'Hello world!' # return the string “Hello World”endTo run the app:> ruby hellow_world.rb
  • 5. Second Hello World AppSinatra configurationSinatra routesSinatra helpersWatch your Request values
  • 6. Sinatra: Helpers, Routes, and Blockshelpers do def format_title(name)name.capitalize # your return value endEndget '/library/:department' do @title = "#{format_title(params[:department])} Department".striphaml :department # invoke a templateend
  • 7. Views with SinatraStandard conventionViews always go in the “views” directoryTemplates marked “layout.ext” are automatically used as wrappers for “content-like templates” like “mycustomdisplay.ext”Static files (stylesheets, images, etc.) are served up out of the “public” directorySupport a wide variety of template options to generate XHTML, HTML5, XML, etc. Can easily define custom formatsIntegration with RACK makes it easy to deal with the parts of an HTTP Request
  • 8. HAML TemplatesHAML – HTML Templates for the LazyAlso bundled with a CSS Template: SASS%html{:"xml:lang"=>"en"} %head %title My Library Web: #{@title} %link{:type=>"text/css",:rel=>"stylesheet",:media=>"screen",:href=>"/stylesheet.css"} %body #pageContent #header %ul.nav %li %a{:href=>"/"} Home #body =yield #footer %p Office of Library Services
  • 9. Where is the Registry?Set configuration options and constants easilySinatra’s integration with rack makes it easy to access and manipulate the contents of the http.request associated
  • 10. What about Testing?Unit tests are built into rackset :environment, :testclass LibraryTest < Test::Unit::TestCase def test_it_says_hello_world browser = Rack::Test::Session.new(Rack::MockSession.new(Sinatra::Application))browser.get '/' assert browser.last_response.ok?assert_equal '<h1>Hello World!</h1>', browser.last_response.body end def test_it_says_hello_to_a_department browser = Rack::Test::Session.new(Rack::MockSession.new(Sinatra::Application))browser.get '/library/ill' assert browser.last_response.body.include?('ill') endend
  • 11. Deployment OptionsLaunch Locally with ruby thin web serverThis is built into the applicationPublish directly to herokuLaunch via apacheproxy_balancer modulepassenger modulengnix
  • 12. Heroku FeaturesRead-only filesystemInstalled as a ruby gemIntegrated with git and sshFree for low-volume applicationsAdd-ons to expand functionalityMemcacheDatabases,DNS, heroku logsGood documentationNot just sinatra, rails and any other rack-based applicationSimilar to the “Google App Engine”
  • 13. Heroku Deployment Ruby Platform as a Service – http://heroku.com/Rails, Sinatra, generic Rack ApplicationsIntegrated directly with git version to controlTo Deploy:create “config.ru” file – defines your rack applicationcreate .gems file – defines libraries your app requiresgit initgit add .git commit –m “Initial Commit”heroku creategit push heroku master
  • 14. Thin Server Configuration--- chdir: /home/kreiss/ruby/lookup/rackup: /home/kreiss/ruby/lookup/config.ruenvironment: productionaddress: 127.0.0.1port: 5000timeout: 30log: /home/kreiss/ruby/lookup/log/thin.logpid: /home/kreiss/ruby/lookup/tmp/pids/thin.pidmax_conns: 1024max_persistent_conns: 512require: []wait: 30servers: 3daemonize: true
  • 15. An Actual ApplicationStandard number checkerWrapper for our web services provided by our ILSEmbed this as a web service in other application/scripts
  • 16. REST-Like InterfaceOutput multiple formatsJSONCustom XML with builder gemXML parsing handled by the nokogiri ruby gem
  • 17. More Complicated Sample Routeget '/:campus/isbn/:isbn' dolookup_base = is_valid_sublibrary(params[:campus]) @number = is_valid_isbn(params[:isbn]) @type = "ISBN" @title = “#{@type}: #{@number} for campus #{lookup_base}" @items = standard_lookup(@number, "bath.isbn", lookup_base) if params[:format] == "xml" builder :bibelsifparams[:format] == "json" @items.to_json elsehaml :standard endend
  • 18. Heroku Deployment486 curl http://cunylookup.heroku.com/laguardia/barcode/33324001754295487 curl http://cunylookup.heroku.com/city/isbn/0800630807488 curl http://cunylookup.heroku.com/city/isbn/0800630807?format=xml489 curl http://cunylookup.heroku.com/city/isbn/0800630807?format=json490 curl http://cunylookup.heroku.com/cun01/isbn/0800630807491 curl http://cunylookup.heroku.com/cun01/isbn/0800630807?format=json492 curl http://cunylookup.heroku.com/cun01/isbn/0800630807?format=xml493 curl http://cunylookup.heroku.com/cun01/isbn/0800630807?format=xml494 curl http://cunylookup.heroku.com/cun01/issn/1092-7735?format=xml495 curl http://cunylookup.heroku.com/city/issn/1092-7735?format=xml496 curl http://cunylookup.heroku.com/laguardia/issn/1092-7735?format=xml497 curl http://cunylookup.heroku.com/laguardia/lccn/96042502?format=xml498 curl http://cunylookup.heroku.com/cun01/lccn/96042502?format=xml
  • 19. GotchasRuby 1.8 v. Ruby 1.9Heroku supports bothGems need to be called differently in ruby 1.8Name your gems sensibly – annoying rubyismDalli: name for memcache gemNokogiri: name for xml processing gemSinatra vs. Sinatra BaseIf you plan to use as middleware in another ruby app you need to define your application with sinatra base
  • 20. Other frameworks in LibrariesRails (Blacklight)PHP Zend (Omeka)Django (Solr front-end)Xerxes (Metasearch)
  • 21. Drupal Platform ServicesViews datasourceDrupal Workflow building capabilitiesWorkflow moduleNew workbench toolkitD7 Rest Server
  • 22. Code4lib ReportLooks of repository middleware