AppObserver.rb Review
-
Here's my version of a global AppObserver for review and comments. My goal is to create a AppObserver that is general in nature and is available for any plugin that needs it.
Users (other scripts in this context) can use it by require'ing the ruby file, and then registering themselves to the instance.
It uses the singleton.rb file from the Ruby language installation. This guarantees there is only 1 instance of the observer.
Here's a small plugin that shows how it might be used (based on Rick's Select at Startup.) Basically, your plugin registers with the AppObserver and implements the same methods as an AppObserver would (i.e. onNewmodel, onOpenModel, onQuit)
require "app_observer.rb" module SelectToolAtStartup def self.onNewModel(args) Sketchup.send_action "selectSelectionTool;" end def self.onOpenModel(args) Sketchup.send_action "selectSelectionTool;" end AppObserver.instance.register self end
The AppObserver handles attaching and detaching itself to the model. All a plugin needs to do is require and register itself to the AppObserver. If there is no plugins that register, AppObserver is never attached. When a plugin registers, the AppObserver attaches itself. When all plugins unregister, the AppObserver also detaches itself. (I'm not sure this is a needed optimization.)
And here's the app observer:
require "sketchup" require "singleton" class AppObserver < Sketchup;;AppObserver include Singleton @attached = false def onNewModel(*args) attach @q.each { |o| o.onNewModel(args) } end def onOpenModel(*args) attach @q.each { |o| o.onOpenModel(args) } end def onQuit(*args) @q.each { |o| o.onQuit(args) } end def attach Sketchup.add_observer(self) @attached = true end private ;attach def detach Sketchup.remove_observer(self) @attached = false end private ;detach def register(o) attach unless @attached @q ||= [] @q.push o unless @q.include? o end def unregister(o) @q.delete(o) detach if @q.empty? end end # class AppObserver
Advertisement