简体   繁体   English

如何为可以访问 cookies 和 session 的控制器创建 rails 服务

[英]How to create a rails service for controllers with access to cookies and session

I want to create a service to DRY my controllers, and make them more readable (and avoid the use of concerns ), but this is not a common service, because it'll be able to get and set cookies and session entries.我想创建一个服务来干燥我的控制器,并使它们更具可读性(并避免使用担忧),但这不是一个常见的服务,因为它能够获取和设置 cookies 和 session 条目。 How can I achieve that?我怎样才能做到这一点?

Thanks!谢谢!

You could create a services something like:您可以创建类似的服务:

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

And then, from within your controller, call it something like:然后,在您的 controller 中,将其命名为:

FooService.call controller: self, other: :args

When called this way, you'll have the methods controller and other in the instance of FooService that hold the values of controller (the one that called the service) and :args , respectively.当以这种方式调用时,您将在FooService的实例中拥有方法controllerother方法,它们分别保存controller (调用服务的那个)和:args的值。 You'll also have the methods session and cookies that are the session and cookies held by the controller . You'll also have the methods session and cookies that are the session and cookies held by the controller . Then, you can do with them as you like.然后,您可以随心所欲地使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM