API / Extension: #<TypeError: reference to deleted Entities>

I have an existing extension that has been in use for a couple years. I am currently changing the workflow to make it easier on users. The new workflow adds a menu option to start from a template file.
When I open the template file directly and run my custom menu option ‘Select Transport Model’ there is no issue. However, when I use the ‘Start from template’ menu option (which opens an existing .skp file without restarting Sketchup) the ‘Select Transport Model’ menu option throws the following error.

#<TypeError: reference to deleted Entities>

C:/Users/cberry/AppData/Roaming/SketchUp/SketchUp 2025/SketchUp/Plugins/cgc_tic-item-importer/lib/utils_import.rb:10:in `add_instance’

The ‘Select Transport Model’ uses the following to build the options:

    containerMenu.add_item(model_name){       

      model_path = File.join(container_dir, container)

      self.import_freight_container(model_path, TicItemImporter::SKU\[:container_offset\] \* TicItemImporter::SKU\[:transport_count\])

    }

Where ‘model_name’ is derived from a set of files in a specified directory. and 'self.import_frieght_container() ’ is a method that places the selected model in the model space based on number of runs of the menu item and sets the model view to ‘zoom extents’

The error remains even after running Statistics/Purge Unused

My current thinking is that when the new file is loaded these ‘Entities’ are sent to garbage collection and no longer able to be referenced. But that feels odd because each ‘entity’ should not be instantiated until the menu option is selected.

Unclear how to resolve this issue. Should I reload the extension when the active model is changed? I will look into how to do that, but any guidance is appreciated.

RESOLVED:

Turns out I was using a scoped variable for Sketchup.entities. I neglected to change the reference when the new file was loaded. The code was referencing the Entities from the closed file.
Added a line to reassign the scoped variable to the new file and all is well.

This is normally done with SketchUp::AppObserver callbacks.

Will attempt to implement in the next refactor.