ActiveRecord Observers Revisted

Posted by Jake Good
on Jan 29, 07

In my previous post, I examined the usage and what I would call problems of current ActiveRecord Observers



I sent it out to the ruby.mn (Minneapolis Ruby User Group) on a whim, to get feedback… and I got quite a bit. In fact, I even got emails from people who have stumbled onto my blog… currently when you search for “ActiveRecord Observers”, my post comes up #4 (strange as how the article is only a few days old).



At any rate… what I mainly got from the feedback, is like the recommended model, my approach isn’t valid either. Yes, Casey, I’m coupling my observer to my observed class… and yes, Brian, the bad coupling now allows the observer to see the observed, which may not be the original intent.



It was also pointed out that my example might not be the best one… there was one simple point I was trying to get across, that my example was not self explanatory enough.



All I wanted to show is that the definition of my class requires that certain data be in the database to do filtering. When the first instance of that class gets loaded and the parser executes the class definition, it will make a database call to build out the definition dynamically (the CommentStatus class)… which in the case of running rake:test on a fresh database, the data will not be there… thus an invalid assumption occurs.



The main problem with my implementation is that it requires data to be present in the system for testing to occur, which IMHO should be taken care of by fixtures… but that’s failing because the fixtures are getting loaded after the assumption needs to run it’s check. It breaks loose coupling and the observer pattern… It’s a bad implementation, I get that.



I think what I was really trying to do was make my implementation behave more like an event driven system, like .Net where instances are responsible for notifying the things that subscribe to their events…Granted it’s not exact but I was trying to get the best thing done with what I had available (aka Observers). Maybe even a mix of “The Hollywood Principle”.



After much discussion, here’s what I realized… I’m going to leave what I have implemented in place cause it readable and it works until I can spend time refactoring it.



I will also try to get a simple Rails application that causes this to break without bad implementation (as I feel like loading fixtures after loading the test environment could break more than it helps)… and see if I can’t get a fix for it to send in a patch.

Comments

Leave a response

Comment