Sha256: 01838297eb8d090b3cde7e39304bdfbad2e6e00bbc618e9380d41928246d136e

Contents?: true

Size: 972 Bytes

Versions: 21

Compression:

Stored size: 972 Bytes

Contents

# frozen_string_literal: true

require 'strscan'

module I18n::Tasks::KeyPatternMatching
  extend self # rubocop:disable Style/ModuleFunction

  MATCH_NOTHING = /\z\A/

  # 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 } * '|' })/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(/\./, '\.')
      .gsub(/\*/, '.*')
      .gsub(/:/, '(?<=^|\.)[^.]+?(?=\.|$)')
      .gsub(/\{(.*?)}/) { "(#{Regexp.last_match(1).strip.gsub(/\s*,\s*/, '|')})" }
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
i18n-tasks-0.9.33 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.32 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.31 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.30 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.29 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.28 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.27 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.26 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.25 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.24 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.23 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.22 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.21 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.20 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.19 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.18 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.17 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.16 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.15 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.9.14 lib/i18n/tasks/key_pattern_matching.rb