在 rails 中提取 i18n 的表单标签

extract form labels for i18n in rails

阅读 ActionView::Helpers::FormHelper,我看到它指出:

The text of label will default to the attribute name unless a translation is found in the current I18n locale (through helpers.label..) or you specify it explicitly.

因此,您应该能够像这样为 post 资源上的 title 标签创建翻译:

app/views/posts/new.html.erb

<% form_for @post do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>
  <%= f.submit %>
<% end %>

config/locales/en.yml

en:
  helpers:
    label:
      post:
        title: 'Customized title'

config/locales/en.yml

en:
  activerecord:
    attributes:
      post:
        title: 'Customized title'

有没有什么方法可以自动提取所有表单标签并将它们的正确键添加到 i18n 语言环境文件中?类似于 i18n-tasks gem 对 I18n.t 定义的键的作用。

我找到了一个解决方案,对于任何想要处理所有用例的人来说,它肯定不是一个通用的解决方案,这个解决方案只是处理来自 脚手架生成器 的默认输出生成这样的表单标签:<%= form.label :username %>。这基本上是 i18n-tasks gem:

的扩展

lib/tasks/scan_resource_form_labels.rb

require 'i18n/tasks/scanners/file_scanner'
class ScanResourceFormLabels < I18n::Tasks::Scanners::FileScanner
  include I18n::Tasks::Scanners::OccurrenceFromPosition

  # @return [Array<[absolute key, Results::Occurrence]>]
  def scan_file(path)
    text = read_file(path)
    text.scan(/^\s*<%= form.label :(.*) %>$/).map do |attribute|
      occurrence = occurrence_from_position(
          path, text, Regexp.last_match.offset(0).first)
      model = File.dirname(path).split('/').last
      # p "================"
      # p model
      # p attribute
      # p ["activerecord.attributes.%s.%s" % [model.singularize, attribute.first], occurrence]
      # p "================"
      ["activerecord.attributes.%s.%s" % [model.singularize, attribute.first], occurrence]
    end
  end
end

I18n::Tasks.add_scanner 'ScanResourceFormLabels'

config/i18n-tasks.yml

(在文件底部添加)

<% require './lib/tasks/scan_resource_form_labels.rb' %>