Skip to content

Instantly share code, notes, and snippets.

@nikz
Forked from NZKoz/gist:608901
Created October 3, 2010 20:39
Show Gist options
  • Save nikz/608913 to your computer and use it in GitHub Desktop.
Save nikz/608913 to your computer and use it in GitHub Desktop.
# use me to deliver emails plz kthx
class Notifier
class Job
VALID_ARGUMENT_TYPES = [ String, Integer, Symbol, ActiveRecord::Base ]
cattr_accessor :ar_prefix
@@ar_prefix = "%OMGSERIALIZEDAR%"
def self.perform(name, args)
NotifierMailer.send(name, *deserialize(args)).deliver!
end
def self.serialize(args)
args.map do |a|
unless VALID_ARGUMENT_TYPES.any? { |t| a.is_a?(t) }
raise ArgumentError, "Invalid argument type #{a.class}. #{a}"
end
if a.is_a?(ActiveRecord::Base)
"#{ar_prefix}:#{a.class}:#{a.id}"
else
a
end
end
end
def self.deserialize(args)
args.map do |a|
if a.is_a?(String) && a.starts_with?(ar_prefix)
junk, klass, id = a.split(":")
klass.constantize.find(id)
else
a
end
end
end
end
cattr_accessor :perform_delayed
@@perform_delayed = false
class << self
def method_missing(name, *args)
args = Job.serialize(args)
if perform_delayed
Resque.enqueue(Job, name, args)
else
Job.perform(name, args)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment