I just hit upon a technique which I haven’t seen before. It is akin to using modules to add behaviour to an object. Let me just present the technique and discuss it afterwards:
1 class Future < ActiveRecord::Base 2 def execute 3 # execute the Future 4 end 5 6 def execute_with_interval 7 execute_without_interval 8 9 if completed? && interval then 10 # schedule a copy of this Future to execute at 11 # a later date/time 12 end 13 end 14 15 alias_method_chain :execute, :interval 16 end
A Future is an object that promises to return a result sometime in the future. I am using it here in the context of a Rails application.
Some of my futures are repeatable tasks, while others are simply one-shot, fire-and-forget. The method I want to introduce is how I added behaviour to an existing method within the same class. I did not include an extra module, nor did I introduce subclasses.
To tell you the truth, I initially implemented
RecurringFuture to add the behaviour there, but I had already created a
RetsFuture that includes additional behaviour specific to talking with a RETS server.
RecurringFuture implementation, I had already implemented
#execute_with_interval and the correct
#alias_method_chain. What I did is I simply pulled the code up, and deleted the now extraneous subclass.
I don’t know if this is a common technique, but I just found it very useful to have a clear separation of concerns: one method executes, the other recurs.