ruby-on-railstaskactivesupport-concern

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

include MyConcern

There, I have an object called my_object, I get the following error when running the task.

NameError: uninitialized constant 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

Btw, the object does have a value.

Am I missing any require? (in my task I am only including the file mentioned above)


Solution

  • 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.

    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