Ruby 递归/嵌套收益率

Ruby 递归/嵌套收益率,ruby,recursion,nokogiri,yield,Ruby,Recursion,Nokogiri,Yield,我有以下两种方法可以使用Nokogiri编辑深度嵌套的XML结构。我想在深入研究结构时删除一些样板文件,所以我想重构这些方法 以下是方法 def create_acl(acl_name, addresses) connection.rpc.edit_config do |x| # `x` is a `Nokogiri::XML::Builder` object. x.configuration do x.firewall do x.family d

我有以下两种方法可以使用Nokogiri编辑深度嵌套的XML结构。我想在深入研究结构时删除一些样板文件,所以我想重构这些方法

以下是方法

def create_acl(acl_name, addresses)
  connection.rpc.edit_config do |x|
    # `x` is a `Nokogiri::XML::Builder` object.
    x.configuration do
      x.firewall do
        x.family do
          x.inet do
            x.filter do
              x.name(acl_name)
              add_acl_whitelist(x, addresses)
              add_acl_blacklist(x)
            end
          end
        end
      end
    end
  end
end

def link_options
  connection.rpc.edit_config do |x|
    # `x` is a `Nokogiri::XML::Builder` object.
    x.configuration do
      x.interfaces do
        x.interface do
          x.name(interface['interface'])
          x.send(:'ether-options') do
            x.send(:'802.3ad') do
              additional.each_pair { |attr, value| x.send(attr) { x.send(value) } }
            end
          end
        end
      end
    end
  end
end
我想我想把它们重构成这样的东西:

def create_acl(acl_name, addresses)
  edit_config(:firewall, :family, :inet, :filter) do |x|
    x.name(acl_name)
    add_acl_whitelist(x, addresses)
    add_acl_blacklist(x)
  end
end

def link_options
  edit_config(:interfaces, :interface) do |x|
    x.name(interface['interface'])
    x.send(:'ether-options') do
      x.send(:'802.3ad') do
        additional.each_pair { |attr, value| x.send(attr) { x.send(value) } }
      end
    end
  end
end

def edit_config(*parents, &block)
  connection.rpc.edit_config do |x|
    # Recursively yield each item in `parents` to x, then yield the given
    # block...
    #
    # Something like this, only with yielding?
    #
    # parents = parents.unshift(:configuration)
    # parents.each { |method| x.send(method, &block) }
  end
end
关于如何嵌套可以传递到该方法中的可变数量的收益率,有什么想法吗?如果不是的话,关于如何用这些方法重构样板文件还有其他想法吗


提前谢谢

查看此样式是否有帮助:

puts "Usual nested way : "
3.times do |x|
    x.times do
        x.times do 
            puts x
        end
    end
end
# => 
# 1
# 2
# 2
# 2
# 2

puts "Using recursion : "
def compact_nested_blocks(*funcs, &leaf_block)
    3.times do |x| # Place the call to your parent block (connection.rpc ...).
        sub_block(x, *funcs, &leaf_block)
    end
end

def sub_block(obj, *funcs, &leaf_block) 
    obj.send(funcs.shift) do
        funcs.empty?? yield(obj) : sub_block(obj, *funcs, &leaf_block)
    end
end

# Call it with your methods instead of 'times'.
compact_nested_blocks(:times, :times) do |x|
    puts x
end
# => 
# 1
# 2
# 2
# 2
# 2
我无法在本地用你的代码测试它。更换所需的核心线路,看看是否足够