Skip to content

Instantly share code, notes, and snippets.

View npj's full-sized avatar

Peter Brindisi npj

  • SoundCloud
  • Berlin
View GitHub Profile
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_filter :find_post
protected
def find_post
unless @post = Post.where(:slug => params[:id]).first
# what do we do here?
class PostObserver
def after_save(post)
Slug[post.slug] = post.id.to_s
return true
end
end
# 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/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/queue/base.rb
class Queue::Base
class << self
def enqueue(object, method, *args)
meta = { 'method' => method }
ensure_queueable!(object, method, *args)
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)
meta = { 'method' => method }
if is_model?(object)
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 })
QUEUE=high,normal,low rake resque:work