- èªåç¨ã®ã¡ã¢ãå
¬éãããã®ã§ããããã¥ã¡ã³ã/ã½ã¼ã¹ã³ã¼ãçãã¾ã¨ããã ãã§è©¦ãã¦ããªãã³ã¼ããå¤ãã®ã§ãä¿¡é ¼æ§ã¯ä½ãã§ãã
request_storeã¨ã¯ï¼
- ãªã¯ã¨ã¹ãæ¯ã«ã°ãã¼ãã«ãªå¤æ°ã使ãã
- â975
å°å
¥
1. ã¤ã³ã¹ãã¼ã«
gem 'request_store'
$ bundle
2. 使ã£ã¦ã¿ã
before_action :set_current_user
def set_current_user
RequestStore.store[:current_user] = current_user
end
RequestStore.store[:current_user]
é¡ä¼¼æ©è½ã¨ã®æ¯è¼
Thread.current
- ã¹ã¬ãããã¼ã«ã«å¤æ°ãã¤ã¾ãã¹ã¬ããåä½ã§ã°ãã¼ãã«ãªå¤æ°ã(ããã¥ã¡ã³ãã«ã¯
not thread-local but fiber-local
ã¨æ¸ãã¦ãã£ããéãããããããã£ããfiber使ãããé£ãã...)
- request_storeã¯å
é¨ã§ã³ã¬ä½¿ã£ã¦ã
Thread.current[:foo] = 0
Thread.current[:foo]
åé¡ç¹
- ã¢ããªãµã¼ãã¯ãªã¯ã¨ã¹ã1ååã§ã¹ã¬ãããçµäºããã次ã®ãªã¯ã¨ã¹ããåãã¹ã¬ããã§å¦çããããã®éã«å¤ããªã»ããããã¦ããªãã®ã§ãååã®å¤ãæã¡è¶ãã¦ãã¾ã
def index
Thread.current[:counter] ||= 0
Thread.current[:counter] += 1
render :text => Thread.current[:counter]
end
Webrickã§ã¯åé¡ãªãããã
ActiveSupport::CurrentAttributes
- ãªã¯ã¨ã¹ãæ¯ã«ãªã»ãããããã¹ã¬ãããã¼ã«ã«ãªå±æ§ãå®ç¾©ã§ãã
- ãã¡ããå
é¨ã§
Thread.current
ãå©ç¨ãã¦ã
- ã¦ã¼ã¹ã±ã¼ã¹ã¨ãã¦ã¯request_idçãæ³å®ãã¦ãã£ã½ã
- Rails5.2ã§è¿½å
- åè: https://github.com/rails/rails/pull/29180
使ãæ¹
- ãã¶ããããªæãï¼èªä¿¡ãªã
class Current < ActiveSupport::CurrentAttributes
attribute :user
end
class ApplicationController < ActionController::Base
before_action :set_current_user
def set_current_user
Current.user = currrent_user
end
end
Current.user
使ãéã®æ³¨æç¹
ã°ã«ã¼ãã«ã«ã¢ã¯ã»ã¹ã§ãã¡ãã
- ã°ã«ã¼ãã«ã«ã¢ã¯ã»ã¹ã§ãã¡ããã®ã§ã
- MVCãå£ãã¦ã«ãªã¹ã«ãªã
- ãã¹ããé£ãããªã
- ã³ã¬ãå¿
è¦ã«ãªãå ´åã¯è¨è¨ãééã£ã¦ããå¯è½æ§ãããã®ã§ãã¾ãã¯è¨è¨ãè¦ç´ã
- CurrentAttributesã®è¨äºã ãã©ãåããã¨ãå½ã¦ã¯ã¾ããã: https://techracho.bpsinc.jp/hachi8833/2017_08_01/43810
ãªã¯ã¨ã¹ãæ¯ã«ãã«ãã¹ã¬ãã使ãã®ã¯NG
ãã¹ã
- ããã«ã¦ã§ã¢ã追å ããå¿
è¦ãã
def app
Rack::Builder.new do
use RequestStore::Middleware
run MyApp
end
end
Rails以å¤ã§ä½¿ã
- ããã«ã¦ã§ã¢ã追å ããã°OK
use RequestStore::Middleware
ãã£ããã³ã¼ããªã¼ãã£ã³ã°
- ã³ã¼ããã¼ã¹ã¯ããªãå°ãã
request_store.gemspec
- ä¾ågem
- rack: Rackããã«ã¦ã§ã¢ã使ããã
lib/request_store.rb
RequestStore
Thread.current[:request_store]
ã便å©ã«æ±ããããã«ããã©ããã¼ã®ãããªã¯ã©ã¹
module RequestStore
def self.store
Thread.current[:request_store] ||= {}
end
...
end
lib/request_store/middleware.rb
RequestStore::Middleware
- ã¬ã¹ãã³ã¹æã«
Thread.current[:request_store]
ãã¯ãªã¢ããRackããã«ã¦ã§ã¢
def call(env)
RequestStore.begin!
response = @app.call(env)
returned = response << Rack::BodyProxy.new(response.pop) do
RequestStore.end!
RequestStore.clear!
end
ensure
unless returned
RequestStore.end!
RequestStore.clear!
end
end
lib/request_store/railtie.rb
- ããã«ã¦ã§ã¢ã追å ããã
åèURL