Search code examples
ruby-on-railsthor

Is there a way to extends a base module when I use thor?


I want to make a batch under a rails project.

I have created a base batch module:

# lib/tasks/batch_base.rb
module Tasks
  class BatchBase
    def run
      # Run something
    end
  end
end

Now I want to make a batch with thor.

# lib/tasks/another_batch.rb
require 'thor'
module Tasks
  class AnotherBatch < Thor
    desc 'test', 'sample'
    def hello(name)
      # Do something
    end
  end
end

Here I want to extends the base batch, but when I try:

class AnotherBatch < BatchBase < Thor
# or
class AnotherBatch < Thor < BatchBase

It doesn't work. Error:

superclass must be a Class (NilClass given) (TypeError)

How can I do it?


Solution

  • If I understand your concerns correctly you should declare your BatchBase as a module and you'll have something like that

     
    module Tasks
      module BatchBase
        def run
        ...
        end
      end
    end 

    require 'thor' module Tasks class AnotherBatch < Thor include BatchBase end end

    Ruby does not have multiple inheritance, you should use mixins instead. You can read more about it here