Skip to content

Instantly share code, notes, and snippets.

View npj's full-sized avatar

Peter Brindisi npj

  • SoundCloud
  • Berlin
View GitHub Profile
# app/models/my_model.rb
class MyModel < ActiveRecord::Base
def async_background_method(arg1, arg2)
Queue::Normal.enqueue(self, :background_method, arg1, arg2)
end
# this happens in the background,
def background_method(arg1, arg2)
# do something that takes a long time...
# app/models/user.rb
class User
class << self
def async_spam_all(email_text)
Queue::Normal.enqueue(self, :spam_all, email_text)
end
def spam_all(email_text)
# app/models/queue/base.rb
class Queue::Base
class << self
def enqueue(object, method, *args)
meta = { 'method' => method }
ensure_queueable!(object, method, *args)
# app/models/queue/base.rb
class Queue::Base
class << self
def enqueue(object, method, *args)
meta = { 'method' => method }
if is_model?(object)
def perform(meta = { }, *args)
if model = meta['class'].constantize.find_by_id(meta['id'])
model.send(meta['method'], *args)
end
end
def enqueue(object, method, *args)
meta = { 'class' => object.class.name, 'method' => method, 'id' => object.id }
Resque.enqueue(self, meta, args)
end
# app/models/queue/base.rb
class Queue::Base
class << self
def enqueue(object, method, *args)
# ...to be continued
end
def perform
# app/models/queue/high.rb
class Queue::High
@queue = :high
def self.enqueue(object, method, *args)
# ...to be continued
end
def self.perform
# ...to be continued
Queue::Normal.enqueue(some_object, :some_method, { 'some_arg' => 1, 'some_other_arg' => 2 })
Queue::High.enqueue(some_object, :some_really_imporant_method, { 'some_arg' => 1, 'some_other_arg' => 2 })
Queue::Low.enqueue(some_object, :some_method_that_can_take_its_time, { 'some_arg' => 1, 'some_other_arg' => 2 })
COUNT=3 QUEUE=high,normal,low rake resque:workers