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.
Yes this is how it must be done.
See the API docs for
You create 1 master AppObserver subclass instance (inside your plugin’ module namespace,) and attach it to the application using
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
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
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
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:
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).
Is there a good workaround to this?
Oh, if I understand this correctly, then AppObserver.expectsStartupModelNotifications returning true is exactly the way to fix this.
Yes, I think the note is very old (and predates the
AppObserver.expectsStartupModelNotifications callback.). But test to be sure.
From what I see expectsStartupModelNotifications does exactly that.
onOpenModel was not called before (on command line opening). But with the method returning true it is called.