Very similar for groups, because groups are disguised components.
That means they have definitions. And their definitions have a separate name
attribute, than the group instances.
But there are a few quirks. The group.description
method is an wrapper for group.definition.description
. (So like a component instance, they share their definitionās description attribute.)
So to find groups through the definition list, we need to filter out the definitions for images and normal components.
dlist = Sketchup.active_model.definitions
grps = dlist.find_all {|d| d.group? }
return if grps.empty? # test for empty array (not found)
gdef = grps.find {|d| d.name == "PocketDoor" }
if gdef # test for nil (not found)
if !gdef.instances.empty?
gdef.instances.find {|i| i.name == "PocketDoor - Master Bath" }
else
nil
end
end
OK?
But you can also simplify the code by combining boolean arguments in the find
and find_all
blocks, and other test expressions:
dlist = Sketchup.active_model.definitions
gdef = dlist.find {|d| d.group? && d.name == "PocketDoor" }
if gdef && !gdef.instances.empty?
gdef.instances.find {|i| i.name == "PocketDoor - Master Bath" }
else
return nil
end
The find
iterator will return nil
if no match is found. (But be careful, as the find_all
iterator always returns an array, so it will be an empty array if no matches are found.)
So to wrap it up in a method:
def find_group_by_name(
definition_name = "Group#1",
instance_name = ""
)
#
if !definition_name.is_a?(String) || !instance_name.is_a?(String)
raise(TypeError,"String arguments required.",caller)
end
#
dlist = Sketchup.active_model.definitions
gdef = dlist.find {|d| d.group? && d.name == definition_name }
if gdef && !gdef.instances.empty?
gdef.instances.find {|i| i.name == instance_name }
else
return nil
end
#
end ###