Determine if component has children?

I have read/searched here for a bit and can’t seem to find a way to tell if a component is nested. Hope I am wrong any suggestions?

Thanks

Entity method “parent”

2 Likes

Thanks!


model = Sketchup.active_model
selset = model.selection

selset.each do|dc|
  dc_parent = dc.parent
  if dc_parent == model
    puts 'parent'
  else
    puts 'child'
  end
end

This works if the parent is at the top model level. I realize now that I need it the other way :man_facepalming:, can I tell if it has children?

Then you should iterate along the component definition entities. If one of them has definition then your component has children.
By the way selection is an array, it’s not neccesary .to_a

1 Like

Here it is:


model = Sketchup.active_model
selset = model.selection

selset.each do |dc|
  cdef = dc.definition
  cdef_ents = cdef.entities
  cdef_ents.each do |entity|
    if entity.respond_to?(:definition)
      puts 'has child'
    else
      puts 'no children'
    end
  end
end

Thanks for the help!

1 Like

NO.
The Selection is an Object, and Includes Enumerable

That’s not why you don’t need to copy the current collection to an array…
…but:

  • There is an Selection #each method to iterate through all of the selected entities. (It is similar method as in a Class: Array (Ruby 2.7.2), but the Selection is not an Array. )
  • During the iteration above the the current collection of selection will not be modified, therefore the .to_a method not necessary, but keep in mind:
    Note:
    Don’t remove content from this collection while iterating over it with #each. This would change the size of the collection and cause elemnts to be skipped as the indices change. Instead copy the current collection to an array using to_a and then use each on the array, when removing content.
3 Likes

Using Enumerable#any?

def has_children?(dc)
  dc.definition.entities.any? { |entity| entity.respond_to?(:definition) }
end

selset.grep(Sketchup::ComponentInstance) do |dc|
  has_children?(dc) ? puts 'has child' : puts 'no children'
end

Or getting parents with children …

def get_parents(selset)
  selset.grep(Sketchup::ComponentInstance).select(&:has_children?)
end

:bulb:

2 Likes