Sha256: 3011ae96cdc5f63bb3fd0a96d21c4fdc70767ee6e7ce67318a5ba6b428fff81c

Contents?: true

Size: 962 Bytes

Versions: 4

Compression:

Stored size: 962 Bytes

Contents

# frozen_string_literal: true
require 'strscan'

module I18n::Tasks::KeyPatternMatching
  extend self
  MATCH_NOTHING = /\z\A/.freeze

  # one regex to match any
  def compile_patterns_re(key_patterns)
    if key_patterns.blank?
      # match nothing
      MATCH_NOTHING
    else
      /(?:#{ key_patterns.map { |p| compile_key_pattern p } * '|'.freeze })/m
    end
  end

  # convert pattern to regex
  # In patterns:
  #      *     is like .* in regexs
  #      :     matches a single key
  #   { a, b.c } match any in set, can use : and *, match is captured
  def compile_key_pattern(key_pattern)
    return key_pattern if key_pattern.is_a?(Regexp)
    /\A#{key_pattern_re_body(key_pattern)}\z/
  end

  def key_pattern_re_body(key_pattern)
    key_pattern.
        gsub(/\./, '\.'.freeze).
        gsub(/\*/, '.*'.freeze).
        gsub(/:/, '(?<=^|\.)[^.]+?(?=\.|$)'.freeze).
        gsub(/\{(.*?)}/) { "(#{$1.strip.gsub /\s*,\s*/, '|'.freeze})" }
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
i18n-tasks-0.9.6 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.5 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.4 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.3 lib/i18n/tasks/key_pattern_matching.rb