在 rails 中提取 i18n 的表单标签

问题描述

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

除非在当前 I18n 语言环境中找到翻译(通过 helpers.label..)或您明确指定,否则标签文本将认为属性名称

因此,您应该能够为帖子资源上的标题标签创建翻译,如下所示:

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,occurrence]
    end
  end
end

I18n::Tasks.add_scanner 'ScanResourceFormLabels'

config/i18n-tasks.yml

(在文件底部添加)

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