sinatra and friends

Post on 15-Jan-2015

2.684 Views

Category:

Technology

3 Downloads

Preview:

Click to see full reader

DESCRIPTION

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

TRANSCRIPT

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-loverRack好き 7/51

Fight with our friends!友と闘え!

8/51

Rack is the best friendRackは最高の友達

9/51

Middlewares in SinatraSinatraでのミドルウェア

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.rumap '/blogs' do run App::SimpleBlogend

map '/us' do run App::UrlShortenerend

14/51

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

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 exampleCRUDの例

Need these friends:必須の友

shotgun

haml

sequel

20/51

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

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 :articleend

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::Modelend

run Sinatra::Application

25/51

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

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

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

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 endend

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 endend

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

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

top related