我在获取Thor时遇到了一些麻烦,因此希望有人可以指出我在做什么错。
我有一个主类class MyApp < Thor
,我想分为多个 namespace 的单独文件,例如thor create:app_type
和thor update:app_type
。我找不到任何示例来说明如何将Thor应用程序分解成几部分,而我尝试过的似乎无效。
例如,我正在尝试从主要的Thor类中突破这一类:
module Things
module Grouping
desc "something", "Do something cool in this group"
def something
....
end
end
end
当我尝试在我的主类(class)中包括或要求这样做时:
class App < Thor
....
require 'grouping_file'
include Things::Grouping
....
end
我得到一个异常(exception):
'<module:Grouping>': undefined method 'desc' for Things::Grouping:Module (NoMethodError)
可能有多个用于Thor任务的 namespace ,如果是的话,如何将其分解,以使您没有一个需要数百行的整体类?
最佳答案
使用总体模块,例如Foo
,在其中您将定义所有子模块和子类。
在单个foo.thor
文件中启动该模块的定义,该文件位于您将运行所有Thor任务的目录中。在此Foo
的foo.thor
模块的顶部,定义此方法:
# Load all our thor files
module Foo
def self.load_thorfiles(dir)
Dir.chdir(dir) do
thor_files = Dir.glob('**/*.thor').delete_if { |x| not File.file?(x) }
thor_files.each do |f|
Thor::Util.load_thorfile(f)
end
end
end
end
然后在主要
foo.thor
文件的底部添加:Foo.load_thorfiles('directory_a')
Foo.load_thorfiles('directory_b')
这将递归包括这些目录中的所有
*.thor
文件。将模块嵌套在主要Foo
模块中,以为您的任务命名。只要您通过上述方法将所有与Thor相关的目录都包括在内,那么文件位于何处或在那时被调用都无关紧要。关于ruby - 如何在单独的类/模块/文件中组合Thor任务?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5729071/