sinatra and friends

52
Rails to Sinatra What's ready Jiang Wu

Upload: jiang-wu

Post on 15-Jan-2015

2.684 views

Category:

Technology


3 download

DESCRIPTION

My presentation on Ruby Kaigi 2010, with title "Rails to Siantra: What's ready"

TRANSCRIPT

Page 1: Sinatra and friends

Rails to Sinatra

What's ready

Jiang Wu

Page 2: Sinatra and friends

Is Mr. Tsuyoshikawa

Here?吉川さんは着たの

か。1/51

Page 3: Sinatra and friends

『Sinatra 1.0 の世界にようこそ』

2/51

Page 4: Sinatra and friends

Minimal Effort最小限の労力

require 'rubygems'require 'sinatra'

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

3/51

Page 5: Sinatra and friends

It's unfair不公平

4/51

Page 6: Sinatra and friends

over one

5/51

Page 7: Sinatra and friends

The answer is friends「友達」がカギ

6/51

Page 8: Sinatra and friends

Sinatra is designed to need friends

Sinatraは友達を前提に設計されている

No Presets設定不要

Pure RubyピュアRuby

Rack-loverRack好き 7/51

Page 9: Sinatra and friends

Fight with our friends!友と闘え!

8/51

Page 10: Sinatra and friends

Rack is the best friendRackは最高の友達

9/51

Page 11: Sinatra and friends

Middlewares in SinatraSinatraでのミドルウェア

Rack::Session::Cookie

Rack::CommonLogger

Rack::MethodOverride

10/51

Page 12: Sinatra and friends

rack-contrib

Rack::Profiler

Rack::JSON-P

Rack::Recaptcha

Rack::MailExceptions

(and more)11/51

Page 13: Sinatra and friends

Rack::Cache

12/51

Page 14: Sinatra and friends

Rack::URLMap

13/51

Page 15: Sinatra and friends

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

# in config.rumap '/blogs' do run App::SimpleBlogend

map '/us' do run App::UrlShortenerend

14/51

Page 16: Sinatra and friends

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

# in config.rumap 'http://blogs.mysite.com/' do run App::SimpleBlogend

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

15/51

Page 17: Sinatra and friends

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

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

16/51

Page 18: Sinatra and friends

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

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

17/51

Page 19: Sinatra and friends

Rack is awesome!

Rack最高!18/51

Page 20: Sinatra and friends

Some common tasks基本タスク

CRUD

Unit Test

Authentication

Ajax

19/51

Page 21: Sinatra and friends

CRUD exampleCRUDの例

Need these friends:必須の友

shotgun

haml

sequel

20/51

Page 22: Sinatra and friends

migrationマイグレーション

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

21/51

Page 23: Sinatra and friends

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

sequel -m migrations -E $DATABASE_URL

22/51

Page 24: Sinatra and friends

rollbackロールバック

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

sequel -m migrations -M 0 -E $DATABASE_URL

23/51

Page 25: Sinatra and friends

app.rb

require 'rubygems'require 'sinatra'require 'blog'

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

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

24/51

Page 26: Sinatra and friends

config.ru

require 'app'require 'sequel'

DB = Sequel.connect ENV['DATABASE_URL']

class Blog < Sequel::Modelend

run Sinatra::Application

25/51

Page 27: Sinatra and friends

run config.ruconfig.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

Page 28: Sinatra and friends

Unit Test

Need these friends:必須の友

Rack::MockRequest

Rspec | Test::Unit | Shoulda

27/51

Page 29: Sinatra and friends

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.okresp.body.should.match(%r{ <title>My Title</title> })

28/51

Page 30: Sinatra and friends

Authentication認証

Need these friends:必須の友

Warden

Rack::OpenID

29/51

Page 31: Sinatra and friends

Strategies認証方式

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

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

30/51

Page 32: Sinatra and friends

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) endend

31/51

Page 33: Sinatra and friends

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 = Failedend

32/51

Page 34: Sinatra and friends

OpenID and OAuth

warden-openid provides

warden-oauth provides

33/51

Page 35: Sinatra and friends

Ajax

Need these friends:必須の友

jQuery

34/51

Page 36: Sinatra and friends

Client-side code

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

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

35/51

Page 37: Sinatra and friends

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 endend

36/51

Page 38: Sinatra and friends

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 endend

37/51

Page 39: Sinatra and friends

Web services may help便利なサービス

38/51

Page 40: Sinatra and friends

Heroku

Minimal effort to deploy app

最小限の労力でアプリをデプロする

39/51

Page 41: Sinatra and friends

just a "push""push"するだけ

wujiang@wujiang-laptop:~/jiangwu.net$ git push heroku masterCounting 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

Page 42: Sinatra and friends

no need to setup system by yourselfセットアップ不要

41/51

Page 43: Sinatra and friends

Disqus

Minimal effort of comment system

最小限の労力でコメントシステムを作る

42/51

Page 44: Sinatra and friends

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

Page 45: Sinatra and friends

Loading読み込み中

44/51

Page 46: Sinatra and friends

Loading Complete読み込み完了

45/51

Page 47: Sinatra and friends

Light but powerful軽くてパワフル

46/51

Page 48: Sinatra and friends

Focus専念

47/51

Page 49: Sinatra and friends

Real Business真の用事

48/51

Page 50: Sinatra and friends

Make friends actively友達をたくさん作ろう!

49/51

Page 51: Sinatra and friends

Questions?質問どうぞ

50/51

Page 52: Sinatra and friends

Thank you!

Especially thanks Masayoki TakaHashi and Eito Katagiri for translations!

http://jiangwu.net

@mastewujiang

51/51