Mat*_*ark 1 ruby ruby-on-rails
我是Rails的新手(即愚蠢,需要一些教学').
我有一个控制器(称之为ControllerFoo
)执行一个特定的任务(theMethod
),这可能在其他控制器(例如,从内部ControllerBar
)有用.所以,当然,该方法被定义为self.theMethod
在ControllerFoo
(这意味着它是一个类的方法,对吗?),并在访问ControllerBar
的ControllerFoo.theMethod
.困惑了吗?
这是问题:ControllerFoo.theMethod
使用会话数据,当调用时ControllerBar
,session是零.实际上,从自身调用时,似乎会话也是零.我想我说的是类方法无法访问会话数据?
<rant> 我讨厌如何在PHP </ rant>之类的任何地方简单地访问会话数据
所以现在,由于我不够聪明,不知道如何正确地做到这一点,我只是在我的应用程序中的几个地方重复了逻辑.但这根本不是干的,我讨厌它.
那么如何在控制器中创建一个可供其他控制器访问的方法,并且还可以访问会话数据?
class ControllerFoo < ApplicationController
def self.theMethod (greeting)
p "#{greeting} #{session[:user]}!"
end
end
class ControllerBar < ApplicationController
def show
ControllerFoo.theMethod("Hello,")
end
end
Run Code Online (Sandbox Code Playgroud)
几个选项......
例如
module SharedModule
def theMethod (greeting)
p "#{greeting} #{session[:user]}!"
end
end
class ControllerFoo < ApplicationController
include SharedModule
end
class ControllerBar < ApplicationController
include SharedModule
def show
theMethod("Hello,")
end
end
Run Code Online (Sandbox Code Playgroud)