Ruby on rails Rails在ActionController和ActiveJob中都使用了一个函数
我们在控制器下的application.rb中有一个通用日志函数。但active job找不到该函数(我假设是因为我们的电子邮件作业扩展了ActiveJob::Base,而我们的控制器引用了ActionController,后者引用了ActionController::Base)Ruby on rails Rails在ActionController和ActiveJob中都使用了一个函数,ruby-on-rails,ruby-on-rails-4,actioncontroller,Ruby On Rails,Ruby On Rails 4,Actioncontroller,我们在控制器下的application.rb中有一个通用日志函数。但active job找不到该函数(我假设是因为我们的电子邮件作业扩展了ActiveJob::Base,而我们的控制器引用了ActionController,后者引用了ActionController::Base) 将日志功能放在哪里,这样我们就可以使代码尽可能保持干燥?因此,在与其他人交谈之后,通过使用lib文件夹并在其中创建模块来确定最佳方案 我们在其中创建了一个名为trackers的文件夹和一个名为tracker.rb的文件
将日志功能放在哪里,这样我们就可以使代码尽可能保持干燥?因此,在与其他人交谈之后,通过使用lib文件夹并在其中创建模块来确定最佳方案 我们在其中创建了一个名为trackers的文件夹和一个名为tracker.rb的文件。下面是它的基本外观片段
module Trackers
module_function
mattr_accessor :controller
def track_action(event_name, event_params)
event_params["time"] ||= Time.now.utc.to_i
# Controller scope only - this only gets executed if the function is called via a controller vs an ActiveJob
if controller
event_params["controller_name"] ||= controller_name
event_params["action_name"] ||= action_name
end
#Other stuff redacted
end
end
在application.rb文件中,我们修改了代码以包含文件夹:
config.autoload_paths += %W(
#{config.root}/lib/
#{config.root}/lib/trackers/
)
在控制器或ActiveJob中的方法中,它被这样调用-
Trackers.track_action("eventName", {
"someVar" => "someValue",
})
另一种选择是使用模型,但我觉得这更像是一个lib函数——我们以后可能会把它变成一个gem
希望这对以后的其他人有帮助