Search code examples
rubysketchup

Add entity to entities collection?


https://developers.google.com/sketchup/docs/ourdoc/entities

I want to add an array of entities to an entities collection, but the entities collection (as you can see in the reference) requires i add them by type, ie. entities.add_edge(). What's the best way to do this for an array of mixed types?

Here's a snippet - the second last line isnt valid (a generic .add doesnt exist)

layers.each do |layer|
    layerEnts = []
    entities.each { |e| layerEnts << e if layer == (e.layer) }
    layerGroup = entities.add_group
    layerGroup.name = layer.name
    layerGroup.entities.add(layerEnts)
end

Solution

  • You can call methods in a dynamic way using send

    Assuming that you can get the type doing layer.type this should solve your problem.

    layerEnts.each do |l|
      type = l.typename.downcase
      layerGroup.entities.send("add_#{type}".to_sym, l)
    end
    

    UPDATE: Just reading the documentation seems that there is actually a method to get the type, it's typename and seems it's camel cased so we need to downcase it.

    https://developers.google.com/sketchup/docs/ourdoc/entity#typename


    Also it seems there are types with more than one word so you need some underscores in there. Here is a solution

    layerEnts.each do |l|
      type = l.typename.gsub(/(.)([A-Z])/,'\1_\2').downcase
      layerGroup.entities.send("add_#{type}".to_sym, l)
    end