SlideShare a Scribd company logo
1 of 52
Download to read offline
Rails to
Sinatra
What's ready

 Jiang Wu
Is Mr.
Tsuyoshikawa
    Here?
吉川さんは着たの
     か。
               1/51
『Sinatra
1.0 の世界
にようこそ』
       2/51
Minimal Effort
    最小限の労力


require 'rubygems'
require 'sinatra'

get '/' do
  "Hello, world!"
end
                     3/51
It's unfair
   不公平




              4/51
over one




           5/51
The answer is friends
      「友達」がカギ




                    6/51
Sinatra is designed to
    need friends
Sinatraは友達を前提に設計されている

 No Presets
 設定不要

 Pure Ruby
 ピュアRuby

 Rack-lover
 Rack好き
                     7/51
Fight with our friends!
        友と闘え!




                     8/51
Rack is the best friend
      Rackは最高の友達




                     9/51
Middlewares in Sinatra
    Sinatraでのミドルウェア

 Rack::Session::Cookie
 Rack::CommonLogger
 Rack::MethodOverride


                         10/51
rack-contrib
Rack::Profiler
Rack::JSON-P
Rack::Recaptcha
Rack::MailExceptions
(and more)
                       11/51
Rack::Cache

          12/51
Rack::URLMap

          13/51
Seperate apps by path
      パスでアプリを分割


    # in config.ru
    map '/blogs' do
      run App::SimpleBlog
    end

    map '/us' do
      run App::UrlShortener
    end

                              14/51
Seperate apps by host
      ホスト名でアプリを分割


 # in config.ru
 map 'http://blogs.mysite.com/' do
   run App::SimpleBlog
 end

 map 'http://us.mysite.com/' do
   run App::UrlShortener
 end

                                     15/51
Directory Structure(1)
      ディレクトリ構成(1)


   - multi/
     - apps/
       | simple_blog_app.rb
       | url_shortener_app.rb
     - views/
       + simple_blog/
       + url_shortener/
     | config.ru

                                16/51
Directory Structure(2)
     ディレクトリ構成(2)


      - multi/
        - simple_blog/
          | app.rb
          | config.ru
          + views/
        - url_shortener/
          | app.rb
          | config.ru
          + views/
        | config.ru

                           17/51
Rack is
awesome!
 Rack最高!
           18/51
Some common tasks
            基本タスク

CRUD
Unit Test
Authentication
Ajax

                    19/51
CRUD example
           CRUDの例

Need these friends:
必須の友

 shotgun
 haml
 sequel
                      20/51
migration
       マイグレーション


# in 1281789589_create_blogs.rb
# touch `date +%s`_create_blogs.rb
Sequel.migration do
  up do
    create_table(:blogs) do
      primary_key :id
    end
  end
end

                                     21/51
run migration
      マイグレーションの実行


sequel -m migrations -E $DATABASE_URL




                                    22/51
rollback
             ロールバック


# "-M 0" means to rollback all
# "-M 0" は全部をロールバックという意味

sequel -m migrations -M 0 -E $DATABASE_URL




                                             23/51
app.rb
require 'rubygems'
require 'sinatra'
require 'blog'

get '/blogs/:id' do |id|
  @blog = Blog[:id => id]
  haml :article
end

post '/blogs/?' do
  @blog = Blog.create(params[:blog])
  redirect "/#{@blog.id}"
end


                                       24/51
config.ru

require 'app'
require 'sequel'

DB = Sequel.connect ENV['DATABASE_URL']

class Blog < Sequel::Model
end

run Sinatra::Application


                                      25/51
run config.ru
             config.ruの実行

~/workspace/sinatra$ shotgun -s thin

==   Shotgun/Thin on http://127.0.0.1:9393/
>>   Thin web server (v1.2.7 codename No Hup)
>>   Maximum connections set to 1024
>>   Listening on 127.0.0.1:9393, CTRL+C to stop




                                                   26/51
Unit Test
Need these friends:
必須の友

 Rack::MockRequest
 Rspec | Test::Unit | Shoulda



                                27/51
Rack::MockRequest
# Mock of a Rack App
# Rack アプリケーションをモックする
req = Rack::MockRequest.new(Sinatra::Application)

# invoke HTTP methods(as in Sinatra)
# HTTPメソッドを呼び出す(Sinatraと同じ)
resp = req.get('/')

# And you get one Rack::MockResponse
# Rack::MockResponseを得る
resp.should.be.kind_of Rack::MockResponse

resp.should.be.ok
resp.body.should.match(%r{ <title>My Title</title> })

                                                    28/51
Authentication
             認証

Need these friends:
必須の友

 Warden
 Rack::OpenID


                        29/51
Strategies
          認証方式

No presetted strategies.
あらかじめセットされた認証方式はない

Adding new strategy is very
easy.
新しい方式を加えるが容易だ




                           30/51
Add new Strategy
# Add to strategies // 認証方式を加える
Warden::Strategies.add(:password) do

  def authenticate!
    u = User.auth(params['username'], params['password'])
    u.nil? ? fail!("Could not log in") : success!(u)
  end
end




                                                            31/51
Use Warden
# must enable session when use warden
# セッションの使用が必須
enable :session

# just as use a rack middleware
# Rackミドルワェアの使用と同じ
use Warden::Manager do |manager|

  # assign the stategies
  # 認証方式を指定する
  manager.default_strategies :password

  # Which Rack App to handle failure?
  # 失敗したらどのRack Appをとうして処理するか
  manager.failure_app = Failed
end


                                         32/51
OpenID and OAuth
warden-openid provides


warden-oauth provides



                         33/51
Ajax
Need these friends:
必須の友

 jQuery




                      34/51
Client-side code

$.post('/blogs', {
  title: 'new title',
  content: '.. some content'
});

// with jquery-form
$('#form').ajaxSubmit();

                               35/51
No respond_to
#   in a rails controller
#   different routes "/:id.:format", "/:id?format=:format"
#   shares the same code
#   パスが異なっていても同じコードを共有している

def show
  respond_to do |format|
    format.json do
      # deal with json
    end
    format.html do
      # deal with html
    end
  end
end

                                                         36/51
Only         case ... when ...
  # use regexp routes
  # 正規表現のルーツを使う

  get %r{^/blogs/:id(.json|.xml)?$} do
    if params[:captures]
      params[:format] = params[:captures][0][1..-1]
    end

    case params[:format]
      when 'json'
        # deal with json
      else
        # deal with html
    end
  end

                                                      37/51
Web services may help
      便利なサービス




                   38/51
Heroku
Minimal effort to deploy app
最小限の労力でアプリをデプロ
する




                          39/51
just a "push"
               "push"するだけ

wujiang@wujiang-laptop:~/jiangwu.net$ git push heroku master
Counting objects: 7, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 1.03 KiB, done.
Total 4 (delta 2), reused 0 (delta 0)

-----> Heroku receiving push
-----> Rack app detected
       Compiled slug size is 340K
-----> Launching...... done
       http://www.jiangwu.net deployed to Heroku




                                                               40/51
no need to
setup system
 by yourself
 セットアップ不要
            41/51
Disqus
Minimal effort of comment
system
最小限の労力でコメントシステ
ムを作る



                           42/51
add commenting
system in one minute
        瞬時にコメント機能を追加

 <section class="comments">
     ...
     <script type="text/javascript"
         src="http://disqus.com/forums/wujiang/embed.js">
     </script>
     ...
 </section>




                                                            43/51
Loading
読み込み中




          44/51
Loading Complete
    読み込み完了




                   45/51
Light but
powerful
軽くてパワフル
        46/51
Focus
 専念
      47/51
Real
Business
 真の用事
        48/51
Make friends actively
    友達をたくさん作ろう!




                   49/51
Questions?
  質問どうぞ

          50/51
Thank you!
Especially thanks Masayoki
TakaHashi and Eito Katagiri
for translations!

http://jiangwu.net
@mastewujiang
                          51/51

More Related Content

What's hot

Writing & Sharing Great Modules on the Puppet Forge
Writing & Sharing Great Modules on the Puppet ForgeWriting & Sharing Great Modules on the Puppet Forge
Writing & Sharing Great Modules on the Puppet ForgePuppet
 
Composer the right way - SunshinePHP
Composer the right way - SunshinePHPComposer the right way - SunshinePHP
Composer the right way - SunshinePHPRafael Dohms
 
Composer for Busy Developers - php|tek13
Composer for Busy Developers - php|tek13Composer for Busy Developers - php|tek13
Composer for Busy Developers - php|tek13Rafael Dohms
 
Session on Launching Selenium Grid and Running tests using docker compose and...
Session on Launching Selenium Grid and Running tests using docker compose and...Session on Launching Selenium Grid and Running tests using docker compose and...
Session on Launching Selenium Grid and Running tests using docker compose and...Agile Testing Alliance
 
Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is DockerNick Belhomme
 
PHP Dependency Management with Composer
PHP Dependency Management with ComposerPHP Dependency Management with Composer
PHP Dependency Management with ComposerAdam Englander
 
B-Translator as a Software Engineering Project
B-Translator as a Software Engineering ProjectB-Translator as a Software Engineering Project
B-Translator as a Software Engineering ProjectDashamir Hoxha
 
Development Setup of B-Translator
Development Setup of B-TranslatorDevelopment Setup of B-Translator
Development Setup of B-TranslatorDashamir Hoxha
 
Zend Framework 1.8 workshop
Zend Framework 1.8 workshopZend Framework 1.8 workshop
Zend Framework 1.8 workshopNick Belhomme
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterZendCon
 
Deployment Tactics
Deployment TacticsDeployment Tactics
Deployment TacticsIan Barber
 
Performance tips for Symfony2 & PHP
Performance tips for Symfony2 & PHPPerformance tips for Symfony2 & PHP
Performance tips for Symfony2 & PHPMax Romanovsky
 
Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016Clark Everetts
 
Php psr standard 2014 01-22
Php psr standard 2014 01-22Php psr standard 2014 01-22
Php psr standard 2014 01-22Võ Duy Tuấn
 
Using Drupal Features in B-Translator
Using Drupal Features in B-TranslatorUsing Drupal Features in B-Translator
Using Drupal Features in B-TranslatorDashamir Hoxha
 
Bfg Ploneconf Oct2008
Bfg Ploneconf Oct2008Bfg Ploneconf Oct2008
Bfg Ploneconf Oct2008Jeffrey Clark
 
PHP & JavaScript & CSS Coding style
PHP & JavaScript & CSS Coding stylePHP & JavaScript & CSS Coding style
PHP & JavaScript & CSS Coding styleBo-Yi Wu
 
Dependency Management with Composer
Dependency Management with ComposerDependency Management with Composer
Dependency Management with ComposerJordi Boggiano
 

What's hot (20)

Writing & Sharing Great Modules on the Puppet Forge
Writing & Sharing Great Modules on the Puppet ForgeWriting & Sharing Great Modules on the Puppet Forge
Writing & Sharing Great Modules on the Puppet Forge
 
Composer the right way - SunshinePHP
Composer the right way - SunshinePHPComposer the right way - SunshinePHP
Composer the right way - SunshinePHP
 
Composer for Busy Developers - php|tek13
Composer for Busy Developers - php|tek13Composer for Busy Developers - php|tek13
Composer for Busy Developers - php|tek13
 
Session on Launching Selenium Grid and Running tests using docker compose and...
Session on Launching Selenium Grid and Running tests using docker compose and...Session on Launching Selenium Grid and Running tests using docker compose and...
Session on Launching Selenium Grid and Running tests using docker compose and...
 
Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is Docker
 
Maven 3.0 at Øredev
Maven 3.0 at ØredevMaven 3.0 at Øredev
Maven 3.0 at Øredev
 
PHP Dependency Management with Composer
PHP Dependency Management with ComposerPHP Dependency Management with Composer
PHP Dependency Management with Composer
 
B-Translator as a Software Engineering Project
B-Translator as a Software Engineering ProjectB-Translator as a Software Engineering Project
B-Translator as a Software Engineering Project
 
Development Setup of B-Translator
Development Setup of B-TranslatorDevelopment Setup of B-Translator
Development Setup of B-Translator
 
Zend Framework 1.8 workshop
Zend Framework 1.8 workshopZend Framework 1.8 workshop
Zend Framework 1.8 workshop
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Deployment Tactics
Deployment TacticsDeployment Tactics
Deployment Tactics
 
Performance tips for Symfony2 & PHP
Performance tips for Symfony2 & PHPPerformance tips for Symfony2 & PHP
Performance tips for Symfony2 & PHP
 
Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016
 
Php psr standard 2014 01-22
Php psr standard 2014 01-22Php psr standard 2014 01-22
Php psr standard 2014 01-22
 
Using Drupal Features in B-Translator
Using Drupal Features in B-TranslatorUsing Drupal Features in B-Translator
Using Drupal Features in B-Translator
 
Bfg Ploneconf Oct2008
Bfg Ploneconf Oct2008Bfg Ploneconf Oct2008
Bfg Ploneconf Oct2008
 
Mcollective introduction
Mcollective introductionMcollective introduction
Mcollective introduction
 
PHP & JavaScript & CSS Coding style
PHP & JavaScript & CSS Coding stylePHP & JavaScript & CSS Coding style
PHP & JavaScript & CSS Coding style
 
Dependency Management with Composer
Dependency Management with ComposerDependency Management with Composer
Dependency Management with Composer
 

Viewers also liked

Rubyconf China
Rubyconf ChinaRubyconf China
Rubyconf ChinaJiang Wu
 
TVS Suzuki JV Split - Analysis on Corp Governance
TVS Suzuki JV Split - Analysis on Corp GovernanceTVS Suzuki JV Split - Analysis on Corp Governance
TVS Suzuki JV Split - Analysis on Corp GovernanceAniruddha Ray (Ani)
 
Ani's Small World - 35 Revolutions Around The Sun
Ani's Small World  - 35 Revolutions Around The SunAni's Small World  - 35 Revolutions Around The Sun
Ani's Small World - 35 Revolutions Around The SunAniruddha Ray (Ani)
 
Hero honda joint venture and split
Hero honda joint venture and splitHero honda joint venture and split
Hero honda joint venture and splitSanjay Safiwala
 
Hero Honda Joint Venture Split
Hero Honda Joint Venture SplitHero Honda Joint Venture Split
Hero Honda Joint Venture SplitAnant Lodha
 

Viewers also liked (6)

Rubyconf China
Rubyconf ChinaRubyconf China
Rubyconf China
 
TVS Suzuki JV Split - Analysis on Corp Governance
TVS Suzuki JV Split - Analysis on Corp GovernanceTVS Suzuki JV Split - Analysis on Corp Governance
TVS Suzuki JV Split - Analysis on Corp Governance
 
Ani's Small World - 35 Revolutions Around The Sun
Ani's Small World  - 35 Revolutions Around The SunAni's Small World  - 35 Revolutions Around The Sun
Ani's Small World - 35 Revolutions Around The Sun
 
T V S
T V ST V S
T V S
 
Hero honda joint venture and split
Hero honda joint venture and splitHero honda joint venture and split
Hero honda joint venture and split
 
Hero Honda Joint Venture Split
Hero Honda Joint Venture SplitHero Honda Joint Venture Split
Hero Honda Joint Venture Split
 

Similar to Sinatra and friends

DevOps in PHP environment
DevOps in PHP environment DevOps in PHP environment
DevOps in PHP environment Evaldo Felipe
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in RustInfluxData
 
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоWebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоGeeksLab Odessa
 
Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular applicationmirrec
 
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB DevroomMore on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB DevroomValeriy Kravchuk
 
DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)Oleg Zinchenko
 
2012 coscup - Build your PHP application on Heroku
2012 coscup - Build your PHP application on Heroku2012 coscup - Build your PHP application on Heroku
2012 coscup - Build your PHP application on Herokuronnywang_tw
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slidesharetomcopeland
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5Darren Craig
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby TeamArto Artnik
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Deepak Garg
 
Control your deployments with Capistrano
Control your deployments with CapistranoControl your deployments with Capistrano
Control your deployments with CapistranoRamazan K
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris Cowan
 
Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015David Alger
 
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...Puppet
 
Challenges of container configuration
Challenges of container configurationChallenges of container configuration
Challenges of container configurationlutter
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsDECK36
 
Jaoo Michael Neale 09
Jaoo Michael Neale 09Jaoo Michael Neale 09
Jaoo Michael Neale 09Michael Neale
 

Similar to Sinatra and friends (20)

DevOps in PHP environment
DevOps in PHP environment DevOps in PHP environment
DevOps in PHP environment
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in Rust
 
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоWebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
 
Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular application
 
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB DevroomMore on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
 
DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)
 
2012 coscup - Build your PHP application on Heroku
2012 coscup - Build your PHP application on Heroku2012 coscup - Build your PHP application on Heroku
2012 coscup - Build your PHP application on Heroku
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshare
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012
 
Control your deployments with Capistrano
Control your deployments with CapistranoControl your deployments with Capistrano
Control your deployments with Capistrano
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015
 
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...
 
Challenges of container configuration
Challenges of container configurationChallenges of container configuration
Challenges of container configuration
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
 
Jaoo Michael Neale 09
Jaoo Michael Neale 09Jaoo Michael Neale 09
Jaoo Michael Neale 09
 

More from Jiang Wu

Python speed up with numba
Python speed up with numbaPython speed up with numba
Python speed up with numbaJiang Wu
 
Implement Web API with Swagger
Implement Web API with SwaggerImplement Web API with Swagger
Implement Web API with SwaggerJiang Wu
 
API documentation with Swagger UI(LT)
API documentation with Swagger UI(LT)API documentation with Swagger UI(LT)
API documentation with Swagger UI(LT)Jiang Wu
 
用Ruby编写博客应用
用Ruby编写博客应用用Ruby编写博客应用
用Ruby编写博客应用Jiang Wu
 
Ruby off Rails---rack, sinatra and sequel
Ruby off Rails---rack, sinatra and sequelRuby off Rails---rack, sinatra and sequel
Ruby off Rails---rack, sinatra and sequelJiang Wu
 

More from Jiang Wu (6)

Python speed up with numba
Python speed up with numbaPython speed up with numba
Python speed up with numba
 
Implement Web API with Swagger
Implement Web API with SwaggerImplement Web API with Swagger
Implement Web API with Swagger
 
API documentation with Swagger UI(LT)
API documentation with Swagger UI(LT)API documentation with Swagger UI(LT)
API documentation with Swagger UI(LT)
 
用Ruby编写博客应用
用Ruby编写博客应用用Ruby编写博客应用
用Ruby编写博客应用
 
JS2
JS2JS2
JS2
 
Ruby off Rails---rack, sinatra and sequel
Ruby off Rails---rack, sinatra and sequelRuby off Rails---rack, sinatra and sequel
Ruby off Rails---rack, sinatra and sequel
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 

Sinatra and friends

  • 2. Is Mr. Tsuyoshikawa Here? 吉川さんは着たの か。 1/51
  • 4. Minimal Effort 最小限の労力 require 'rubygems' require 'sinatra' get '/' do "Hello, world!" end 3/51
  • 5. It's unfair 不公平 4/51
  • 6. over one 5/51
  • 7. The answer is friends 「友達」がカギ 6/51
  • 8. Sinatra is designed to need friends Sinatraは友達を前提に設計されている No Presets 設定不要 Pure Ruby ピュアRuby Rack-lover Rack好き 7/51
  • 9. Fight with our friends! 友と闘え! 8/51
  • 10. Rack is the best friend Rackは最高の友達 9/51
  • 11. Middlewares in Sinatra Sinatraでのミドルウェア Rack::Session::Cookie Rack::CommonLogger Rack::MethodOverride 10/51
  • 13. Rack::Cache 12/51
  • 14. Rack::URLMap 13/51
  • 15. Seperate apps by path パスでアプリを分割 # in config.ru map '/blogs' do run App::SimpleBlog end map '/us' do run App::UrlShortener end 14/51
  • 16. Seperate apps by host ホスト名でアプリを分割 # in config.ru map 'http://blogs.mysite.com/' do run App::SimpleBlog end map 'http://us.mysite.com/' do run App::UrlShortener end 15/51
  • 17. Directory Structure(1) ディレクトリ構成(1) - multi/ - apps/ | simple_blog_app.rb | url_shortener_app.rb - views/ + simple_blog/ + url_shortener/ | config.ru 16/51
  • 18. Directory Structure(2) ディレクトリ構成(2) - multi/ - simple_blog/ | app.rb | config.ru + views/ - url_shortener/ | app.rb | config.ru + views/ | config.ru 17/51
  • 20. Some common tasks 基本タスク CRUD Unit Test Authentication Ajax 19/51
  • 21. CRUD example CRUDの例 Need these friends: 必須の友 shotgun haml sequel 20/51
  • 22. migration マイグレーション # in 1281789589_create_blogs.rb # touch `date +%s`_create_blogs.rb Sequel.migration do up do create_table(:blogs) do primary_key :id end end end 21/51
  • 23. run migration マイグレーションの実行 sequel -m migrations -E $DATABASE_URL 22/51
  • 24. rollback ロールバック # "-M 0" means to rollback all # "-M 0" は全部をロールバックという意味 sequel -m migrations -M 0 -E $DATABASE_URL 23/51
  • 25. app.rb require 'rubygems' require 'sinatra' require 'blog' get '/blogs/:id' do |id| @blog = Blog[:id => id] haml :article end post '/blogs/?' do @blog = Blog.create(params[:blog]) redirect "/#{@blog.id}" end 24/51
  • 26. config.ru require 'app' require 'sequel' DB = Sequel.connect ENV['DATABASE_URL'] class Blog < Sequel::Model end run Sinatra::Application 25/51
  • 27. run config.ru config.ruの実行 ~/workspace/sinatra$ shotgun -s thin == Shotgun/Thin on http://127.0.0.1:9393/ >> Thin web server (v1.2.7 codename No Hup) >> Maximum connections set to 1024 >> Listening on 127.0.0.1:9393, CTRL+C to stop 26/51
  • 28. Unit Test Need these friends: 必須の友 Rack::MockRequest Rspec | Test::Unit | Shoulda 27/51
  • 29. Rack::MockRequest # Mock of a Rack App # Rack アプリケーションをモックする req = Rack::MockRequest.new(Sinatra::Application) # invoke HTTP methods(as in Sinatra) # HTTPメソッドを呼び出す(Sinatraと同じ) resp = req.get('/') # And you get one Rack::MockResponse # Rack::MockResponseを得る resp.should.be.kind_of Rack::MockResponse resp.should.be.ok resp.body.should.match(%r{ <title>My Title</title> }) 28/51
  • 30. Authentication 認証 Need these friends: 必須の友 Warden Rack::OpenID 29/51
  • 31. Strategies 認証方式 No presetted strategies. あらかじめセットされた認証方式はない Adding new strategy is very easy. 新しい方式を加えるが容易だ 30/51
  • 32. Add new Strategy # Add to strategies // 認証方式を加える Warden::Strategies.add(:password) do def authenticate! u = User.auth(params['username'], params['password']) u.nil? ? fail!("Could not log in") : success!(u) end end 31/51
  • 33. Use Warden # must enable session when use warden # セッションの使用が必須 enable :session # just as use a rack middleware # Rackミドルワェアの使用と同じ use Warden::Manager do |manager| # assign the stategies # 認証方式を指定する manager.default_strategies :password # Which Rack App to handle failure? # 失敗したらどのRack Appをとうして処理するか manager.failure_app = Failed end 32/51
  • 34. OpenID and OAuth warden-openid provides warden-oauth provides 33/51
  • 36. Client-side code $.post('/blogs', { title: 'new title', content: '.. some content' }); // with jquery-form $('#form').ajaxSubmit(); 35/51
  • 37. No respond_to # in a rails controller # different routes "/:id.:format", "/:id?format=:format" # shares the same code # パスが異なっていても同じコードを共有している def show respond_to do |format| format.json do # deal with json end format.html do # deal with html end end end 36/51
  • 38. Only case ... when ... # use regexp routes # 正規表現のルーツを使う get %r{^/blogs/:id(.json|.xml)?$} do if params[:captures] params[:format] = params[:captures][0][1..-1] end case params[:format] when 'json' # deal with json else # deal with html end end 37/51
  • 39. Web services may help 便利なサービス 38/51
  • 40. Heroku Minimal effort to deploy app 最小限の労力でアプリをデプロ する 39/51
  • 41. just a "push" "push"するだけ wujiang@wujiang-laptop:~/jiangwu.net$ git push heroku master Counting objects: 7, done. Delta compression using up to 2 threads. Compressing objects: 100% (4/4), done. Writing objects: 100% (4/4), 1.03 KiB, done. Total 4 (delta 2), reused 0 (delta 0) -----> Heroku receiving push -----> Rack app detected Compiled slug size is 340K -----> Launching...... done http://www.jiangwu.net deployed to Heroku 40/51
  • 42. no need to setup system by yourself セットアップ不要 41/51
  • 43. Disqus Minimal effort of comment system 最小限の労力でコメントシステ ムを作る 42/51
  • 44. add commenting system in one minute 瞬時にコメント機能を追加 <section class="comments"> ... <script type="text/javascript" src="http://disqus.com/forums/wujiang/embed.js"> </script> ... </section> 43/51
  • 46. Loading Complete 読み込み完了 45/51
  • 48. Focus 専念 47/51
  • 50. Make friends actively 友達をたくさん作ろう! 49/51
  • 52. Thank you! Especially thanks Masayoki TakaHashi and Eito Katagiri for translations! http://jiangwu.net @mastewujiang 51/51