開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Ruby 2.3 (プログラミング言語)
Head First Ruby (Jay McGavren (著)、O'Reilly Media)のChapter 15.(Saving and Loading Data: Keep It Around)、Setting up a Sinatra route for a POST request、EXERCISE(No. 7718)を取り組んでみる。
EXERCISE(No. 7718)
コード(Emacs)
#!/usr/bin/env ruby2.3
# -*- coding: utf-8 -*
require 'sinatra'
get('/form') do
erb :form
end
post('/convert') do
fahrenheit = @params['temperature'].to_f
celsius = (fahrenheit - 32) / 1.8
format("%0.1f degrees Faharenheit is %0.1f degrees Celsius.",
fahrenheit, celsius)
end
<!doctype html>
<html>
<body>
<form method="post" action="/convert">
<label for="temperature">Degrees Fahrenheit:</label>
<input id="temperature" type="text" name="temperature">
<input type="submit">
</form>
</body>
</html>
入出力結果(Terminal)
$ ./app.rb [2016-10-09 00:46:02] INFO WEBrick 1.3.1 [2016-10-09 00:46:02] INFO ruby 2.3.1 (2016-04-26) [x86_64-darwin15] == Sinatra (v1.4.7) has taken the stage on 4567 for development with backup from WEBrick [2016-10-09 00:46:02] INFO WEBrick::HTTPServer#start: pid=35901 port=4567 ::1 - - [09/Oct/2016:00:46:06 +0900] "GET / HTTP/1.1" 404 462 0.0323 ::1 - - [09/Oct/2016:00:46:06 JST] "GET / HTTP/1.1" 404 0 - -> / ::1 - - [09/Oct/2016:00:46:08 +0900] "GET / HTTP/1.1" 404 462 0.0015 ::1 - - [09/Oct/2016:00:46:08 JST] "GET / HTTP/1.1" 404 462 - -> / ::1 - - [09/Oct/2016:00:46:09 +0900] "GET /form HTTP/1.1" 200 237 0.0103 ::1 - - [09/Oct/2016:00:46:09 JST] "GET /form HTTP/1.1" 200 237 - -> /form ::1 - - [09/Oct/2016:00:46:10 +0900] "GET /form HTTP/1.1" 200 237 0.0066 ::1 - - [09/Oct/2016:00:46:10 JST] "GET /form HTTP/1.1" 200 237 - -> /form ::1 - - [09/Oct/2016:00:46:16 +0900] "POST /convert HTTP/1.1" 200 49 0.0015 ::1 - - [09/Oct/2016:00:46:16 JST] "POST /convert HTTP/1.1" 200 49 http://localhost:4567/form -> /convert C-c C-c== Sinatra has ended his set (crowd applauds) [2016-10-09 00:46:21] INFO going to shutdown ... [2016-10-09 00:46:22] INFO WEBrick::HTTPServer#start done. $
0 コメント:
コメントを投稿