如何解决从delay_job调用时,与I18n.fallbacks相关的Rails ActionView崩溃
我正试图从我的rails 4应用程序发送电子邮件(控制台的精简版):
> ActionMailer::Base.mail(from: 'mail@example.com',to: 'foo@example.com',subject: 'test',body: "Hello,you've got mail!").deliver_later
该邮件将由delay_lob发送,在我的本地测试设置中,我会这样触发它:
> Delayed::Job.last.invoke_job
但是作业崩溃并显示以下消息:
Devise::Mailer#invitation_instructions: processed outbound mail in 56234.1ms
Performed ActionMailer::DeliveryJob from DelayedJob(mailers) in 56880.04ms
TypeError: no implicit conversion of nil into Array
from /Users/de/.rvm/gems/ruby-2.4.0/gems/actionview-4.2.10/lib/action_view/lookup_context.rb:51:in `concat'
from /Users/de/.rvm/gems/ruby-2.4.0/gems/actionview-4.2.10/lib/action_view/lookup_context.rb:51:in `block in <class:LookupContext>'
from /Users/de/.rvm/gems/ruby-2.4.0/gems/actionview-4.2.10/lib/action_view/lookup_context.rb:39:in `initialize_details'
from /Users/de/.rvm/gems/ruby-2.4.0/gems/actionview-4.2.10/lib/action_view/lookup_context.rb:205:in `initialize'
...
我查看了lookup_context.rb:51
GitHub的代码,问题出在这里:
register_detail(:locale) do
locales = [I18n.locale]
locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks # < crashes here
# from the debugger I got:
# I18n.locale => :de
# I18n.fallbacks => {:en=>[]}
显然,后备不包含我的语言环境(:de
),该语言环境会导致nil
异常。
显然I18n.fallbacks配置不正确。
问题:我该如何解决?
解决方法
在这个博客文章的帮助下,我得到了答案:https://sjoker.net/2013/12/30/delayed_job-and-localization/
它包含了我所需要的一半。提议的解决方案如下:
为了从创建作业时开始传播状态,必须将该状态存储到数据库中的作业对象上,从而将该状态转移到调用作业的时间。
在博客文章中,作者仅存储当前语言环境以在邀请时对邮件进行本地化。但是,我还需要存储fallbacks
,这需要一点序列化。
这是我的解决方案:
# Add a state attributes to delayed_jobs Table
class AddLocaleToDelayedJobs < ActiveRecord::Migration
def change
change_table :delayed_jobs do |t|
t.string :locale # will hold the current locale when the job is invoked
t.string :fallbacks # ...
end
end
end
# store the state when creating the job
Delayed::Worker.lifecycle.before(:enqueue) do |job|
# If Locale is not set
if(job.locale.nil? || job.locale.empty? && I18n.locale.to_s != I18n.default_locale.to_s)
job.locale = I18n.locale
job.fallbacks = I18n.fallbacks.to_json
end
end
# retrieve the state when invoking the job
Delayed::Worker.lifecycle.around(:invoke_job) do |job,&block|
# Store locale of worker
savedLocale = I18n.locale
savedFallbacks = I18n.fallbacks
begin
# Set locale from job or if not set use the default
if(job.locale.nil?)
I18n.locale = I18n.default_locale
else
h = JSON.parse(job.fallbacks,{:symbolize_names => true})
I18n.fallbacks = h.each { |k,v| h[k] = v.map(&:to_sym) } # any idea how parse this more elegantly?
I18n.locale = job.locale
end
# now really perform the job
block.call(job)
ensure
# Clean state from before setting locale
I18n.locale = savedLocale
I18n.fallbacks = savedFallbacks
end
end
,
您需要像下面这样配置默认和后备区域设置
config.i18n.default_locale = :de
config.i18n.fallbacks = { de: :en }
请尝试这个。如果找不到:en
,它将回退到:de
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。