Help us understand the problem. What is going on with this article?

Sinatraの使い方あれこれ

More than 3 years have passed since last update.

Sinatraの使い方あれこれ

異なるルートで同じ対応をしたい

DRYを実践したい

require 'sinatra'

['/one', '/two', '/three'].each do |route|
    get rounte do
        "Triggered #{route} via GET"
    end
    post route do
        "Triggered #{route} via POST"
    end
end

RESTリクエストのパラメータを受け取りたい

例えばこんなリクエスト

http://my.server.address/function?key1=value1&key2=value2&key3=value3

こんなふうに受けることができる

require 'sinatra'

get '/function' do
    params['key1']
    params['key2']
    params['key3']
end

正規表現を用いたルート

require 'sinatra'

get %r{/\A((?:sp|gr)eedy)\z} do |c|
    "You got cought in the #{c} route!"
end

別のルートへリダイレクトする

require 'sinatra'

get '/redirect' do
    redirect 'http://www.google.com'
end

get '/redirect2' do
    redirect 'http://www.google.com', 301
end

ステータスコード301は「Moved Permanently」
デフォルトは302の「Temporary redirection」

静的なファイルを見せる

require 'sinatra'

get '/public.html' do
end

publicフォルダが使われる。例えばpublicフォルダの中にjavascrptsフォルダがあるとすると、http://localhost:4567/javascriptsでアクセスできる。

Erbファイルを見せる

まずviewsフォルダを作る。

require 'sinatra'

get '/index' do
    erb :index
end

Erbファイルに変数を渡す

require '/home' do
    @name = 'Random User'
    erb :home
end

インスタンス変数にアクセスする。

home.erb
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Using variables</title>
</head>
<body>
  <h1>Hello, <%= @name %>!</h1>
</body>
</html>

評価したい文は<%= %>タグで囲む。ループによる制御構造などは<% %>で囲む。

事前・事後に処理したいことがあるとき

require 'sinatra'

before do
    @before_value = 'foo'
end

get '/' do
    "before_value has been set to #{@before_value}"
end

after do
    puts "After Filter called to perform some task"
end

"After Filter called to perform some task" はターミナルに出力される

404 Not Foundのカスタマイズ

require 'sinatra'

before do
    content_type :txt
end

not_found do
    "Whoops! You requested a route that wasn't available."
end

500 Internal Server Errorのカスタマイズ

require 'sinatra'

...

error do
    "Y U NO WORK?"
end

Session管理

require 'sinatra'

configure do
    enable :sessions
end

before do
    content_type :txt
end

get '/set' do
    session[:foo] = Time.now
    "Session value set."
end

get '/fetch' do
    "Session value: #{session[:foo]}"
end

セッションをクリアするには

get '/logout' do
    session.clear
    redirect 'fetch'
end

Cookieの利用

require 'sinatra'

get '/' do
    response.set_cookie "foo", "bar"
    "Cookie set. Would you like to <a href=\"/read\">read it</a>?"
end

get '/read'
    "Cookie has a value of: #{request.cookies['foo']}."
end

get '/delete'
    response.delete_cookie "foo"
    "Cookie has been deleted."
end

ファイル添付

require 'sinatra'

before do
    content_type :txt
end

get '/attachment' do
    attachment 'name_your_attachment.txt'
    "Here's what will be sent downstream, in an attachment called 'name_your_attachment.txt'."
end

ブログやってます:PAPA-tronix !

Feel-Physics
今はHoloLensのアプリを開発しており、技術記事はすべてブログ( http://weed.nagoya )に書いています。以前はSwift、OpenCV+Python、JavaScript、Objective-Cを書いていました。
http://weed.nagoya
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした