Rename Layer0 attempt causes silent failure of code block

It gave me a “headache” for a few hours wondering what the heck is going on… I thought I’d tell you so that it would be easier for you later. :innocent:

So the issue is if I wanted to rename all layers (allow me to use the API terms) I was lazy enough to not exclude the “Layer0” because this cannot be renamed anyway.

Oh yes, as assumed the “Layer0” wasn’t renamed but then the start_operation-commit_operation also wasn’t take effect. What? Why?
Perhaps renaming layers not recorded like the page (Scene) operation?.. this is against what I learned till now.

I thought - beside many other things - I’d create a cpoint, to see if that would fix the creation of the undo stack. Nope! Even the cpoint wasn’t created! So something in my code “backwardly” prevent to create dwge?

Checked in SU2017, 2020, 2021… all behave same, syntax okay…

As I shot the point of “joke” already above: the solution/conclusion is:
Do not try to rename “Layer0”!

The original code is without the commented line, un-comment it, then you get the code running as it should.
Both version are in the animation.

Happy Weekend! :beers:

def rename(backup_names = {})
  model = Sketchup.active_model
  layers = model.layers
  model.start_operation("Rename Tags", true)
  cp = model.entities.add_cpoint(ORIGIN)
  layers.each{|layer|
    # next if layer.name == "Layer0"
    backup_names[layer.entityID] = layer.name
    layer.name += "_-#{layer.entityID}"
  }
  model.commit_operation
  backup_names
end
rename

renameLayer0

PS. You can give same name of existing page for a new page (scene) using Ruby API. Be careful! I told you! :wink:

2 Likes

The layer list [tags] is always returned with Layer0 / Untagged as the first item, so iterate the layers omitting the first item…

#...
layers.to_a[1..-1].each{|layer|
    backup_names[layer.entityID] = layer.name
    layer.name += "_-#{layer.entityID}"
  }
#...
2 Likes

Just a note that entity IDs are not persistent, so rerunning the code again in a later session might result in trying to rename two layers with the same entity ID.

Perhaps use #persistent_id for SU 2020 and later?

I know the code was just a simple snippet to reproduce the scenario.
In actual usage, should the loop skip layer-tags already renamed ?

1 Like

The #persistent_id I used originally, but wanted to check the issue in SU2017… :slight_smile: . Anyway any random number sequence is okay for my use! But thanks for notice!

It is one time rename, then the layer may be deleted, or renamed back to original name… (study for myself…yet :innocent: )

BTW. If you try to rename a layer to the name of existing layer the issue is same as you try to rename “Layer0”.

We dislike silent failures !

They do not indicate where the code has failed.

I agree! At least one was hunted again!