[英]How to create a rails service for controllers with access to cookies and session
我想創建一個服務來干燥我的控制器,並使它們更具可讀性(並避免使用擔憂),但這不是一個常見的服務,因為它能夠獲取和設置 cookies 和 session 條目。 我怎樣才能做到這一點?
謝謝!
您可以創建類似的服務:
class FooService
delegate *%w(
session
cookies
), to: :controller
class << self
def call(args={})
new(args).call
end
end # Class Methods
#=====================================================================
# Instance Methods
#=====================================================================
def initialize(args)
args.each do |k,v|
class_eval do
attr_accessor k
end
send("#{k}=",v)
end
end
def call
end
end
然后,在您的 controller 中,將其命名為:
FooService.call controller: self, other: :args
當以這種方式調用時,您將在FooService
的實例中擁有方法controller
和other
方法,它們分別保存controller
(調用服務的那個)和:args
的值。 You'll also have the methods session
and cookies
that are the session and cookies held by the controller
. 然后,您可以隨心所欲地使用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.