概要
もしリクエストごとに毎回初期化したい場合は before などを使いましょう
環境
- macOS 11.6.2
- Ruby 3.0.3p157
- Sinatra 2.1.0
動作確認用のコード
- vim test.rb
require 'sinatra/base'
class TestWeb < Sinatra::Base
def initialize()
super
puts "initialize"
@age = (0..100).to_a.sample
end
configure do
puts "configure"
set :color, ['blue', 'red', 'green'].sample
end
get '/' do
ret = "#{@age.to_s}, #{settings.color}"
puts ret
ret
end
end
-
vim config.ru
require './test'
run TestWeb
-
bundle exec rackup config.ru
- curl localhost:9292
configure
2022-01-27 10:38:45 +0900 Thin web server (v1.8.1 codename Infinite Smoothie)
2022-01-27 10:38:45 +0900 Maximum connections set to 1024
2022-01-27 10:38:45 +0900 Listening on localhost:9292, CTRL+C to stop
initialize
4, blue
::1 - - [27/Jan/2022:10:38:46 +0900] "GET / HTTP/1.1" 200 7 0.0144
4, blue
::1 - - [27/Jan/2022:10:38:47 +0900] "GET / HTTP/1.1" 200 7 0.0012
4, blue
::1 - - [27/Jan/2022:10:38:48 +0900] "GET / HTTP/1.1" 200 7 0.0011
4, blue
::1 - - [27/Jan/2022:10:38:48 +0900] "GET / HTTP/1.1" 200 7 0.0009
4, blue
::1 - - [27/Jan/2022:10:38:49 +0900] "GET / HTTP/1.1" 200 7 0.0015
ずっと同じ値が返ってくることがわかる
before を使う
- vim test.rb
require 'sinatra/base'
class TestWeb < Sinatra::Base
def initialize()
super
puts "initialize"
@age = (0..100).to_a.sample
end
configure do
puts "configure"
set :color, ['blue', 'red', 'green'].sample
end
before do
@age = (0..100).to_a.sample
@color = ['blue', 'red', 'green'].sample
end
get '/' do
ret = "#{@age.to_s}, #{@color}"
puts ret
ret
end
end
-
vim config.ru
require './test'
run TestWeb
-
bundle exec rackup config.ru
- curl localhost:9292
configure
2022-01-27 10:40:33 +0900 Thin web server (v1.8.1 codename Infinite Smoothie)
2022-01-27 10:40:33 +0900 Maximum connections set to 1024
2022-01-27 10:40:33 +0900 Listening on localhost:9292, CTRL+C to stop
initialize
9, green
::1 - - [27/Jan/2022:10:40:34 +0900] "GET / HTTP/1.1" 200 8 0.0398
59, blue
::1 - - [27/Jan/2022:10:40:35 +0900] "GET / HTTP/1.1" 200 8 0.0025
86, green
::1 - - [27/Jan/2022:10:40:35 +0900] "GET / HTTP/1.1" 200 9 0.0008
95, green
::1 - - [27/Jan/2022:10:40:36 +0900] "GET / HTTP/1.1" 200 9 0.0016
81, blue
::1 - - [27/Jan/2022:10:40:36 +0900] "GET / HTTP/1.1" 200 8 0.0011
93, blue
::1 - - [27/Jan/2022:10:40:37 +0900] "GET / HTTP/1.1" 200 8 0.0012
72, red
::1 - - [27/Jan/2022:10:40:38 +0900] "GET / HTTP/1.1" 200 7 0.0011
毎回違う
Tips
ちなみに configure ないではインスタンス変数に値を設定できないので set メソッドを使って設定し参照する場合は settings を使います
逆に before では set は使えません
Sinatra のインスタンス変数の扱うは少し面倒です
0 件のコメント:
コメントを投稿