Search code examples
ruby-on-railsruby-on-rails-5rails-i18ni18n-tasks

extract form labels for i18n in rails


Reading up on ActionView::Helpers::FormHelper, I see that it states:

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.

So you should be able to create a translation for a title label on a post resource like this:

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'

or

config/locales/en.yml

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

Is there any way of automatically extracting all form labels and adding the correct keys for them to the i18n locale files? Similarly to what the i18n-tasks gem does for I18n.t defined keys.


Solution

  • I found a solution which is certainly not going to be a universal solution for anyone wanting to handle all use cases, this one simply handles the default output from a scaffolding generator which produces form labels like this: <%= form.label :username %>. This is basically an extension for the 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

    (add this at the bottom of the file)

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