What is the quickest way to get a component definition?

I added many defintions, and kept its guid like this:

definition = Sketchup.active_model.definitions.add(defintion_name)
definition.set_attribute("MYDIC", "origuid", definition.guid)

After, I iterated Sketchup.active_model.definitions to read its attributes to find out the origuid to get what definition I wanted. But when the number of definitions increased, it was time-consuming to find out the right definition.

Is there a quick way to get a definition. I am wondering if the index of a definition is a possible solution. Save the index when adding a definition, then access it by the index after. How can I get the index of a definition when it is added. If it will change when adding instances to it?

https://ruby-doc.org/core-2.7.1/Array.html#method-i-index

https://ruby-doc.org/core-2.7.1/Array.html#method-i-rindex

definition = Sketchup.active_model.definitions.add(defintion_name)
definition_index = Sketchup.active_model.definitions.index(definition)

(However I wonder if the definition_index keeps pointing to the right definition or not if you are further manipulating the definitionlist…??)

If you used the #each method to iterate… then could be good to try:
https://ruby-doc.org/core-2.7.1/Enumerable.html#method-i-find

Thanks a lot. Yes, adding definition A, and its index is 1. If adding more definitions and manipulating the defintion A, does its index 1 change or not?

Why don’t you try it? :wink:

Thanks, I will try :grinning_face_with_smiling_eyes:

1 Like

If it works then you do not need the attributes at all :slight_smile: …BUT if someone else (e.g the user manually or other extension) will delete one of the definition then your definition_index will be useless. :blush:

1 Like

You can also use #persistent_id with definitions from SU 2020.1 and higher.

There is a fast model-wide search method … Model#find_entity_by_persistent_id

If you want to stay with the GUID (which changes each time the definition is edited,) then you can use the Model#find_entity_by_id method (it searches for matching entityID or GUID.)


ADD: These methods should be faster because they do the iteration on the C-side rather than the Ruby-side.