Ruby on rails 3.1 如何更改Rails语言环境文件中插值变量的大小写?
将Rails 3.1.3与Ruby 1.9.3p0结合使用 我发现,默认情况下,Rails不会对表单按钮使用句子大小写。例如,它不生成“更新用户”按钮,而是生成“更新用户”按钮 按钮名称来自。有没有一种方法可以创建一个默认值来关闭模型名称?上的RubyonRails指南i18n部分没有介绍这一点,因此可能不可能。以下操作不起作用:Ruby on rails 3.1 如何更改Rails语言环境文件中插值变量的大小写?,ruby-on-rails-3.1,internationalization,Ruby On Rails 3.1,Internationalization,将Rails 3.1.3与Ruby 1.9.3p0结合使用 我发现,默认情况下,Rails不会对表单按钮使用句子大小写。例如,它不生成“更新用户”按钮,而是生成“更新用户”按钮 按钮名称来自。有没有一种方法可以创建一个默认值来关闭模型名称?上的RubyonRails指南i18n部分没有介绍这一点,因此可能不可能。以下操作不起作用: en: helpers: submit: update: 'Update %{model}.downcase' 总的来说,我很高兴能找到有关
en:
helpers:
submit:
update: 'Update %{model}.downcase'
总的来说,我很高兴能找到有关语言环境YAML文件语法的参考。《i18n指南》涵盖了一些语法,但找到所有感叹号、各种日期/时间格式等的文档会很有帮助。或者我应该为此使用Ruby哈希而不是YAML文件?经过进一步研究,我得出结论,对插值进行这种操作是不可能的,至少使用YAML语言环境文件 YAML在此有文档记录,不支持字符串操作:
Ruby本地化的主页在这里:
从那里,我们找到默认i18ngem的代码,并深入到插值代码。它使用
sprintf
进行插值:该代码“主要基于Masao Mutoh的gettext字符串插值扩展”:
该扩展名有一个格式化数字的示例: 字符串的
。
“%$firstname},%$familyname}”%%{firstname=>“Masao”,:familyname=>“Mutoh”}
使用字段类型指定格式,如d(十进制)、f(浮点),。。。
“%
在sprintf
上的文档中,有很多方法可以格式化数字,但没有更改字符串大小写的操作。我通过更改I18n插值解决了这个问题。请将以下代码放在初始值设定项目录中:
module I18n
# Implemented to support method call on translation keys
INTERPOLATION_WITH_METHOD_PATTERN = Regexp.union(
/%%/,
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/, # matches placeholders like "%<foo>.d"
/%\{(\w+)\.(\w+)\}/, # matches placeholders like "%{foo.upcase}"
)
class << self
def interpolate_hash(string, values)
string.gsub(INTERPOLATION_WITH_METHOD_PATTERN) do |match|
if match == '%%'
'%'
else
key = ($1 || $2 || $4).to_sym
value = values.key?(key) ? values[key] : raise(MissingInterpolationArgument.new(values, string))
value = value.call(values) if value.respond_to?(:call)
$3 ? sprintf("%#{$3}", value) : ( $5 ? value.send($5) : value)
end
end
end
end
end
并测试它:
require 'test_helper'
class I18nTest < ActiveSupport::TestCase
should 'interpolate as usual' do
assert_equal 'Show Customer', I18n.interpolate("Show %{model}", model: 'Customer')
end
should 'interpolate with number formatting' do
assert_equal 'Show many 100', I18n.interpolate("Show many %<kr>2d", kr: 100)
assert_equal 'Show many abc', I18n.interpolate("Show many %<str>3.3s", str: 'abcde')
end
should 'support method execution' do
assert_equal 'Show customer', I18n.interpolate("Show %{model.downcase}", model: 'Customer')
end
end
需要“测试助手”
类I18nTest
create: 'Opprett %{model.downcase}'
require 'test_helper'
class I18nTest < ActiveSupport::TestCase
should 'interpolate as usual' do
assert_equal 'Show Customer', I18n.interpolate("Show %{model}", model: 'Customer')
end
should 'interpolate with number formatting' do
assert_equal 'Show many 100', I18n.interpolate("Show many %<kr>2d", kr: 100)
assert_equal 'Show many abc', I18n.interpolate("Show many %<str>3.3s", str: 'abcde')
end
should 'support method execution' do
assert_equal 'Show customer', I18n.interpolate("Show %{model.downcase}", model: 'Customer')
end
end