简体   繁体   English

如何在rakefile(task)Rails中包含关注点?

[英]How to include a concern in rakefile(task) Rails?

I have a concern I want to use in a task let's call it 'MyConcern', I include it like this 我有一个要在任务中使用的问题,我们称之为“ MyConcern”,我将其包括在内

include MyConcern

There, I have an object called my_object, I get the following error when running the task. 在那里,我有一个名为my_object的对象,运行任务时出现以下错误。

NameError: uninitialized constant MyConcern NameError:未初始化的常量MyConcern

Including the file like this instead of the above way: 包括这样的文件,而不是上面的方法:

require File.dirname(__FILE__) + '/../../app/controllers/concerns/my_concern'

I get the following error, when running the task: 运行任务时出现以下错误:

NameError: undefined local variable or method `my_object' for main:Object NameError:main:Object的未定义局部变量或方法“ my_object”

Btw, the object does have a value. 顺便说一句,对象确实具有一个值。

Am I missing any require? 我是否缺少任何要求? (in my task I am only including the file mentioned above) (在我的任务中,我仅包含上述文件)

I made it work by creating a service, this one includes the concern file, in that way I'm able to use the objects of the concern. 我通过创建一个服务来使其工作,该服务包括关注文件,这样我就可以使用关注的对象。 I'm still not sure if that's the right way to do it, but it works. 我仍然不确定这是否是正确的方法,但是它可以工作。

In services folder MyService.rb in it the code. 在服务文件夹 MyService.rb中的代码。

class MyService
 include MyConcern

 def initialize; end
 def execute
  #stuff I have in my concern (for instance *my_object*)
 end
end

In the task I just use the service as usual. 在任务中,我照常使用服务。

MyService.new

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

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