Wednesday, May 21, 2014

Rails: Specify Time.zone in delayed job

Add the following code to the project's config/initializers/delayed_job.rb

The method_missing chain will add the current Time.zone.name to the
function's argument.

The Time.zone.name will be popped by the PerformableMethod.perform chain.


Delayed::DelayProxy.class_eval do

# Embed the current time zone name to delayed job's arguments when
# adding delayed job from delay() method.
def method_missing_with_custom_time_zone(method, *args)
raise "Time zone is nil" if Time.zone.nil?
args << {:custom_time_zone => Time.zone.name}
result = method_missing_without_custom_time_zone(method, *args)
result
end
alias_method_chain :method_missing, :custom_time_zone

end

Delayed::PerformableMethod.class_eval do

# Read time zone from job's argument.
def perform_with_custom_time_zone
if self.args.last.is_a?(Hash) &&
!self.args.last[:custom_time_zone].nil?
Time.zone = args.pop[:custom_time_zone]
else
raise "Custom time zone is missing from the arguments."
end
perform_without_custom_time_zone
end
alias_method_chain :perform, :custom_time_zone

end

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.