简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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