[英]Rails4 accessing params and session from gem
I am building a gem that needs to access GET params and current session. 我正在构建需要访问GET参数和当前会话的gem。
Module MyGem
class MyClass
def write_to_session
session[:user_id] = nil if params[:logout]
end
end
end
The code above just doesn't work because sessions and params are accessible only in the controller. 上面的代码不起作用,因为只能在控制器中访问会话和参数。 In another similar question someone suggested to pass params to the class
在另一个类似的问题中,有人建议将参数传递给全班
Module MyGem
class MyClass
def initialize(params)
@params = params
end
def write_to_session
if @params[:param]
#Do stuff...
end
end
end
But I wonder if it's possible to just have those variables without passing them end 但是我想知道是否有可能只包含那些变量而不传递它们结束
Manipulating a session in a class is fine - it's just another storage location. 在课程中处理会话很好-这只是另一个存储位置。 Better to abstract it and not clutter up the controller code.
最好对其进行抽象处理,而不要弄乱控制器代码。
Just initialize the class with a session 只需使用会话初始化类
def initialize(session, params)
Then do everything you need 然后做你需要的一切
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.