我在Ruby中有一个像这样工作的DSL:
desc 'list all todos'
command :list do |c|
c.desc 'show todos in long form'
c.switch :l
c.action do |global,option,args|
# some code that's not relevant to this question
end
end
desc 'make a new todo'
command :new do |c|
# etc.
end
一位开发人员建议我将我的DSL增强为不需要将c
传递到command
块,因此不需要所有c.
里面的方法;据推测,他暗示我可以使下面的代码工作相同:
desc 'list all todos'
command :list do
desc 'show todos in long form'
switch :l
action do |global,option,args|
# some code that's not relevant to this question
end
end
desc 'make a new todo'
command :new do
# etc.
end
command
的代码类似于
def command(*names)
command = make_command_object(..)
yield command
end
我尝试了几件事而无法让它发挥作用;我无法弄清楚如何将command
块中的代码的上下文/绑定更改为与默认值不同。
关于这是否可能以及我如何做的任何想法?
答案 0 :(得分:31)
粘贴此代码:
def evaluate(&block)
@self_before_instance_eval = eval "self", block.binding
instance_eval &block
end
def method_missing(method, *args, &block)
@self_before_instance_eval.send method, *args, &block
end
有关详情,请参阅这篇非常好的文章here
答案 1 :(得分:10)
也许
def command(*names, &blk)
command = make_command_object(..)
command.instance_eval(&blk)
end
可以在命令对象的上下文中评估块。
答案 2 :(得分:4)
class CommandDSL
def self.call(&blk)
# Create a new CommandDSL instance, and instance_eval the block to it
instance = new
instance.instance_eval(&blk)
# Now return all of the set instance variables as a Hash
instance.instance_variables.inject({}) { |result_hash, instance_variable|
result_hash[instance_variable] = instance.instance_variable_get(instance_variable)
result_hash # Gotta have the block return the result_hash
}
end
def desc(str); @desc = str; end
def switch(sym); @switch = sym; end
def action(&blk); @action = blk; end
end
def command(name, &blk)
values_set_within_dsl = CommandDSL.call(&blk)
# INSERT CODE HERE
p name
p values_set_within_dsl
end
command :list do
desc 'show todos in long form'
switch :l
action do |global,option,args|
# some code that's not relevant to this question
end
end
将打印:
:list
{:@desc=>"show todos in long form", :@switch=>:l, :@action=>#<Proc:0x2392830@C:/Users/Ryguy/Desktop/tesdt.rb:38>}
答案 3 :(得分:2)
我写了一个处理这个问题的类,并处理@instance_variable访问,嵌套等等。这是另一个问题的写作: