How to change case of interpolated variables in Rails locale file?

前端 未结 2 1062
南笙
南笙 2021-02-08 04:50

Using Rails 3.1.3 with Ruby 1.9.3p0.

I\'ve discovered that by default, Rails does not use sentence case for form buttons. For example, instead of an \"Update user\" but

2条回答
  •  灰色年华
    2021-02-08 05:01

    I have solved this problem by changing the I18n interpolation. Put the following code in your initializers directory:

    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 "%.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
    

    Now, this is what you can do in your locale file:

    create: 'Opprett %{model.downcase}'
    

    and test it:

    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 %2d", kr: 100)
        assert_equal 'Show many abc', I18n.interpolate("Show many %3.3s", str: 'abcde')
      end
    
      should 'support method execution' do
        assert_equal 'Show customer', I18n.interpolate("Show %{model.downcase}", model: 'Customer')
      end
    
    end
    

提交回复
热议问题