Permalink
Browse files

Added Module#handle_asynchronously that allows you to mark methods fo…

…r async processing (Michael Koziarski)

This is useful when you have methods you want handled async in the production environment, but not require special case code.

config/environments/production.rb:

config.after_initialize do
  SomeModel.handle_asynchronously :some_method!
end

Thanks
  • Loading branch information...
1 parent cf4ad9f commit dbc5e37c4d313cb2b85701999adff490df0c272b @tobi tobi committed Feb 20, 2009
Showing with 36 additions and 7 deletions.
  1. +11 −1 lib/delayed/message_sending.rb
  2. +4 −4 lib/delayed/worker.rb
  3. +2 −1 lib/delayed_job.rb
  4. +4 −1 spec/database.rb
  5. +15 −0 spec/delayed_method_spec.rb
View
12 lib/delayed/message_sending.rb
@@ -3,5 +3,15 @@ module MessageSending
def send_later(method, *args)
Delayed::Job.enqueue Delayed::PerformableMethod.new(self, method.to_sym, args)
end
- end
+
+ module ClassMethods
+ def handle_asynchronously(method)
+ without_name = "#{method}_without_send_later"
+ define_method("#{method}_with_send_later") do |*args|
+ send_later(without_name, *args)
+ end
+ alias_method_chain method, :send_later
+ end
+ end
+ end
end
View
8 lib/delayed/worker.rb
@@ -4,10 +4,10 @@ class Worker
cattr_accessor :logger
self.logger = if defined?(Merb::Logger)
- Merb.logger
- elsif defined?(RAILS_DEFAULT_LOGGER)
- RAILS_DEFAULT_LOGGER
- end
+ Merb.logger
+ elsif defined?(RAILS_DEFAULT_LOGGER)
+ RAILS_DEFAULT_LOGGER
+ end
def initialize(options={})
@quiet = options[:quiet]
View
3 lib/delayed_job.rb
@@ -5,7 +5,8 @@
require File.dirname(__FILE__) + '/delayed/job'
require File.dirname(__FILE__) + '/delayed/worker'
-Object.send(:include, Delayed::MessageSending)
+Object.send(:include, Delayed::MessageSending)
+Module.send(:include, Delayed::MessageSending::ClassMethods)
if defined?(Merb::Plugins)
Merb::Plugins.add_rakefiles File.dirname(__FILE__) / '..' / 'tasks' / 'tasks'
View
5 spec/database.rb
@@ -35,5 +35,8 @@
# Purely useful for test cases...
class Story < ActiveRecord::Base
- def tell; text; end
+ def tell; text; end
+ def whatever(n, _); tell*n; end
+
+ handle_asynchronously :whatever
end
View
15 spec/delayed_method_spec.rb
@@ -112,6 +112,21 @@ def read(story)
job.payload_object.method.should == :read
job.payload_object.args.should == ["AR:Story:#{story.id}"]
job.payload_object.perform.should == 'Epilog: Once upon...'
+ end
+
+ it "should call send later on methods which are wrapped with handle_asynchronously" do
+ story = Story.create :text => 'Once upon...'
+
+ Delayed::Job.count.should == 0
+
+ story.whatever(1, 5)
+
+ Delayed::Job.count.should == 1
+ job = Delayed::Job.find(:first)
+ job.payload_object.class.should == Delayed::PerformableMethod
+ job.payload_object.method.should == :whatever_without_send_later
+ job.payload_object.args.should == [1, 5]
+ job.payload_object.perform.should == 'Once upon...'
end
end

0 comments on commit dbc5e37

Please sign in to comment.