dav*_*000 36 ruby metaprogramming block
我在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
Run Code Online (Sandbox Code Playgroud)
一位开发人员建议我将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
Run Code Online (Sandbox Code Playgroud)
代码command看起来像
def command(*names)
command = make_command_object(..)
yield command
end
Run Code Online (Sandbox Code Playgroud)
我尝试了几件事而无法让它发挥作用; 我无法弄清楚如何将command块内代码的上下文/绑定更改为与默认值不同.
关于这是否可能以及我如何做的任何想法?
Jat*_*tra 32
粘贴此代码:
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
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅此处非常好的文章
Son*_*tos 10
也许
def command(*names, &blk)
command = make_command_object(..)
command.instance_eval(&blk)
end
Run Code Online (Sandbox Code Playgroud)
可以在命令对象的上下文中评估块.
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
Run Code Online (Sandbox Code Playgroud)
将打印:
:list
{:@desc=>"show todos in long form", :@switch=>:l, :@action=>#<Proc:0x2392830@C:/Users/Ryguy/Desktop/tesdt.rb:38>}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19119 次 |
| 最近记录: |