module GettextI18nRailsJs::Parser::Base

Attributes

gettext_function[W]

The gettext function name can be configured at the module level as gettext_function. This is to provide a way to avoid conflicts with other javascript libraries. You only need to define the base function name to replace “_” and all the other variants (s_, n_, N_) will be deduced automatically.

Public Instance Methods

gettext_function() click to toggle source
# File lib/gettext_i18n_rails_js/parser/base.rb, line 42
def gettext_function
  @gettext_function ||= "__"
end
parse(file, _msgids = []) click to toggle source

We’re lazy and klumsy, so this is a regex based parser that looks for invocations of the various gettext functions. Once captured, we scan them once again to fetch all the function arguments. Invoke regex captures like this:

javascript source: “#{ __(‘hello’) } #{ __(”wor)ld“) }” matches: [0]: __(‘hello’) [1]: __ [2]: ‘hello’

javascript source: __(‘item’, ‘items’, 33) matches: [0]: __(‘item’, ‘items’, 33) [1]: __ [2]: ‘item’, ‘items’, 33

handlebars source: “{{ _ ”foo“}}” matches: [0]: __(‘foo’) [1]: __ [2]: ‘foo’

handlebars source: “{{ _ ”foo“ ”foos“ 3}}” matches: [0]: __(‘foo’, ‘foos’, 3) [1]: __ [2]: ‘foo’, ‘foos’, 3

The PO file outputs to a “” string. single quotes are unescped (if they are escaped) double quotes are escaped (if they are not already escaped)

# File lib/gettext_i18n_rails_js/parser/base.rb, line 78
def parse(file, _msgids = [])
  collect_for(file) do |function, arguments, line|
    key = arguments.scan(
      /('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/
    ).collect do |match|
      contents = match.first[1..-2]
      contents.gsub(/\\'/, "'").gsub(/(?<=[^\\])"/, "\\\"")
    end.join(separator_for(function))

    next if key == ""

    results_for(key, file, line)
  end
end

Protected Instance Methods

cleanup_multiline_line(value) click to toggle source
# File lib/gettext_i18n_rails_js/parser/base.rb, line 95
def cleanup_multiline_line(value)
  result = value.chomp
  result.strip
end
cleanup_value(value) click to toggle source
# File lib/gettext_i18n_rails_js/parser/base.rb, line 100
def cleanup_value(value)
  value
    .tr("\n", "\n")
    .tr("\t", "\t")
    .tr("\0", "\0")
end
results_for(key, file, line) click to toggle source
# File lib/gettext_i18n_rails_js/parser/base.rb, line 115
def results_for(key, file, line)
  [
    cleanup_value(key),
    [file, line].join(":")
  ]
end
separator_for(value) click to toggle source
# File lib/gettext_i18n_rails_js/parser/base.rb, line 107
def separator_for(value)
  if value == "n#{gettext_function}"
    "\000"
  else
    "\004"
  end
end