Ruby Observer Existence Check
-
Is there any way to check to see if an entity already has an observer attached to it?
I am using:
class MyInstanceObserver < Sketchup;;InstanceObserver def onChangeEntity(entity) #puts "onChangeEntity; #{entity}" end endand then
my_openings = ent.grep(Sketchup;;ComponentInstance).find_all {|oi| oi.definition.name.include?('OPENING') } my_openings.each do |oi| next unless oi.valid? oi.add_observer(MyInstanceObserver.new) endBut would prefer not to blindly attached an observer always. This loop will have been run previously.
-
How about doing it this way.
Outside of any of your methods...@@obs = MyInstanceObserver.new() unless @@obsThat only runs once and its reference can then be used thus:
oi.remove_observer(@@obs) oi.add_observer(@@obs)Attempting to remove a non-existent observer does NOT raise an error.
So in this way just one instance of the observer is only ever attached to an instance. -
-
You usually set
@@obs = nilinside a class [outside of any method].
Then within one of that class's methods [likeinitialize()] you can set it to be a proper reference - but just the once.
In a class it needs to be@@obs = ...to persist across instances of the class.
A@obs = ...in a class only exists during that one instance of the class.In my example I set it only if it's not already set [i.e. it is
nil].You can set
@obs = ...within a module, outside of any of its methods and that then persists thereafter.Since I didn't have your whole code I guessed...

-
Thanks TIG. Have not gotten very advanced with Classes etc. so just a simple module. Appreciate the explanation.
-
@tig said:
You can set @obs = ... within a module, outside of any of its methods and that then persists thereafter.
This is true because, a module is an instance of class
Module.@hank said:
Have not gotten very advanced with Classes etc. so just a simple module.
The
Classclass is the direct child class of classModule. So classes inherit all ofModule's functionality, and get a little bit of their own (ie, a few extra methods and the ability to have many instance copies of themselves, that can hold their own instance variable values.)
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better π
Register LoginAdvertisement