-
-
Save nikz/608913 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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