我正在开发自定义DSL以生成树状结构的文件夹和文件
FoldersFilesGenerator::DSL.setup do
root_folder_1 do
root_folder_file_1
subfolder_1 do
subfolder_file_1
subfolder_file_2
sub_subfolder do
...
end
end
subfolder_2 do
...
end
root_folder_file_2
end
root_folder_2 do
...
end
end
PATH = 'path/to/folders_tree.rb'
#FoldersFilesGenerator::Generator.new.generate
def generate
instance_eval(File.read(PATH), File.basename(PATH), 0)
end
module FoldersFilesGenerator
class DSL
attr_accessor :current_path
def self.setup(*args, &block)
new.instance_eval &block
end
def initialize
@current_path = 'initial/root/folder'
end
def method_missing(m, *args, &block)
if block_given?
#need help here
self.current_path = renew_path(@current_path)
FileUtils.mkdir_p current_path #create nested folder
instance_eval(&block)
else
FileCreator.create(m, @current_path) #create file on a current tree level
end
end
private
def renew_path(current_path)
end
end
end
我假设我的工作路径只有当我深入潜水或出现在我的DSL块树结构中时才会改变,因此我需要使用current_path
方法重新分配我的renew_path
,但我完全搞砸了我的代码这里。请帮忙。
解决方案可能完全不同。我需要的就是我的DSL就像我描述的那样。
谢谢。
答案 0 :(得分:1)
不确定您希望renew_path
做什么。它应该像这样简单:
if block_given?
remembered_path = current_path
self.current_path = File.join(current_path, m.to_s)
FileUtils.mkdir_p current_path #create nested folder
instance_eval(&block)
self.current_path = remembered_path
else