类似以下示例代码:
models:
mymodel:
description: it has <%= Arbitrary::Ruby::Code::Inside.and_a_variable %>
因此t('models.mymodel.description')
,给定以下内容:
module Arbitrary
module Ruby
module Code
class Inside
def self.and_a_variable
'a variable'
end
end
end
end
end
将导致:
'it has a variable'
只是出于好奇,类似的事情可能发生吗?
是和否。
简单的答案是否定的——I18n-gem在simple后端没有内置的ERB加载程序。它也没有像Rails对一些配置文件那样通过ERB传递任何其他类型(YAML或JSON(。
它确实有一个内置的.rb
加载程序。它真的可以用来做任何事情,只要对内容进行评估就会产生哈希:
# config/locales/en.rb
{
en: {
hello: "dlroW olleH".reverse
}
}
# config/locales/fr.rb
# lets go crazy and load a translation file from a remote server
require 'json'
require 'net/http'
res = Net::HTTP.get_response(
# does not actually exist
URI('http://www.example.com/locales/fr.json')
)
JSON.parse(res.body)
也有可能创建一个加载器方法,通过ERB
:传递locales/*.erb
文件
module ErbLoader
def load_erb(filename)
begin
template = ERB.new(File.read(filename))
context = binding
YAML.parse(template.result(context))
rescue TypeError, ScriptError, StandardError => e
raise InvalidLocaleData.new(filename, e.inspect)
end
end
end
I18n::Backend::Simple.include(ErbLoader)
请参阅I18n::Backend::Base#load_file以了解其工作原理。
您还可以创建自己的后端,通过ERB传递.yml
文件。I18Ngem实际上是从头开始构建的,可以通过不同的后端进行扩展以存储翻译。
简短的回答是否定的。这是不可能的。您只注入值,它实际上并不运行ruby
代码。