SketchUp Ruby API - 删除所有图层时出现 ArgumentError

SketchUp Ruby API - ArgumentError when delete all layers

我制作了一个脚本来删除从 .dwg 文件导入的所有图层:

# import the dwg file
show_summary = false
if Sketchup.active_model.import file_path, show_summary

    # delete all layer
    protected_layers = ['Layer0', '! 3D', '! AutoCad']
    10.times do
        Sketchup.active_model.definitions.purge_unused
        Sketchup.active_model.layers.purge_unused

        Sketchup.active_model.layers.each { |layer|
            layer_name = layer.name
            if not layer.deleted? and not protected_layers.include? layer_name  
                puts "\tdeleted"
                Sketchup.active_model.layers.remove layer
            end
        }
    end
end

当我导入一个大的 dwg 文件时,所有图层都不会立即导入(大约 100 个图层)...所以我添加了一个 10.times 循环以完全删除所有图层。我的脚本可以完美运行,直到还剩下 10 层。我收到这样的错误:

Error: #<ArgumentError: layer doesn't belong to this model>

那么如何检查我的图层是否已经被删除?我尝试了这些解决方案,但似乎没有人奏效

我创建了一个解决方案 Sketchup.active_model.layers[l.name].nil? 以防止层已被移除。这是我的解决方案示例

layers.take_while{|l| not l.deleted? and not layers[l.name].nil? }.each { |layer|
    puts layer.name
    unless protected_layers.include? layer.name  
        puts "\t[*] deleted"
        layers.remove layer
    else
        puts "\t[ ] undeleted"
    end
}

您正在迭代要从中删除元素的集合。这绝不是一件安全的事情。

将图层缓存到一个数组并对其进行迭代。

这是一个例子:

model = Sketchup.active_model
# Map layer names to layers - as object comparison is much faster than string
# comparisons.
protected_layers = ['Layer0', '! 3D', '! AutoCad'].map { |layer_name|
  model.layers[layer_name]
}
# Start an operation as this keeps the undo stack clean and makes the script
# fun faster.
model.start_operation('Remove Layers', true)
model.layers.to_a.each { |layer|
  next if layer.deleted? || protected_layers.include?(layer)
  model.layers.remove(layer)
}
model.commit_operation