I want to create observers for a number of entities which would trigger a method when the entities change.
But how to do this across Sketchup Sessions? I could run an initialization method at beginning of each Session recreating the observers. Is there a way to trigger a method automatically upon loading an extension? Anyone attempted anything like this?
This may be my 8th programming language, but I’m completely new to Ruby.
You create 1 master AppObserver subclass instance (inside your plugin’ module namespace,) and attach it to the application using Sketchup::add_observer().
ADD (2022-02-14): Since a module is an instance of class Module and an extension will only ever need 1 AppObserver instance, the extension submodule itself can act as the singleton AppObserver object for the extension. This simplifies code. See example link below.
Within the AppObserver callbacks onNewModel() and onOpenModel() you attach a new instance of your plugin’s custom Sketchup::ModelObserver subclass, passing in the model instance reference as an argument with the ::new() constructor.
Within your model observer’s initialize(model) method you can attach new instances of your custom EntitiesObserver subclass to whatever entities collection object that exist at that time. (Which will always be at least the model level entities, even be it empty.)
You can also at this time attach other observer subclass instances to other collection objects that belong to the model, such as the Definitions, Materials, Pages, Selection, and Styles collections.
You could also attach a new Sketchup::EntityObserver subclass instance, to specific drawing objects, by iterating Entities collections, and checking for some property or perhaps your plugin’s custom AttributeDictionary (use “AuthorNamespace_PluginName” as the dictionary name,…) with a certain attribute set to some predetermined value.
ADD (2022-02-14): I’ve since posted an example here:
I am trying to do something similar, but I have run into this:
AppObserver.onOpenModel
NOTE: If a skp file is loaded via the command line or double-clicking on
a skp in explorer (which is also is the command line) then this
observer will not be called. The Ruby interpreter in SketchUp is
initialized after command line processing so the observer won’t
be added in time to get the notification.
Opening a .skp file by double clicking is fairly common I would think. But in this case any of the functionality implemented as above would not be active (no ModelObserver would be created).