Rails ActionView中与I18n相关的崩溃.从delayed_job调用时出现故障



我正试图从我的rails 4应用程序发送一封电子邮件,就像这样(控制台的浓缩版(:

> ActionMailer::Base.mail(from: 'mail@example.com', to: 'foo@example.com', subject: 'test', body: "Hello, you've got mail!").deliver_later

邮件将由delayed_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:51GitHub的代码,问题在这里:

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=>[]}

很明显,fallbacks不包含导致nil异常的区域设置(:de(。

显然,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 }

请试试这个。如果未找到:de,它将回退到:en

最新更新