Skip to content

A custom scanner example

Paolo Brasolin edited this page Nov 8, 2018 · 10 revisions

Multiple scanners are available since v0.9.

The example below scans for all instances of = page_title in haml and slim files and considers them as t('.page_title') calls.

# lib/my_custom_scanner.rb
require 'i18n/tasks/scanners/file_scanner'
class MyCustomScanner < I18n::Tasks::Scanners::FileScanner
  include I18n::Tasks::Scanners::RelativeKeys
  include I18n::Tasks::Scanners::OccurrenceFromPosition

  # @return [Array<[absolute key, Results::Occurrence]>]
  def scan_file(path)
    text = read_file(path)
    text.scan(/^\s*=\s*page_title\b/).map do |_match|
      occurrence = occurrence_from_position(
          path, text, Regexp.last_match.offset(0).first)
      [absolute_key('.page_title', path), occurrence]
    end
  end
end

I18n::Tasks.add_scanner 'MyCustomScanner', only: %w(*.haml *.slim)
# config/i18n-tasks.yml.erb
<% require './lib/my_custom_scanner' %>

Here we are inheriting from a built-in file scanner, but in general this is not required. See the files in the scanners module to learn more.

NB: The example above is for illustration purposes only. The same can be much more easily achieved with the built-in PatternMapper (see the initializer).