Sha256: 6681d024163a0311d17720b3e165339241bd571da5e3b7aecd3b7813d8f9edab

Contents?: true

Size: 1.32 KB

Versions: 17

Compression:

Stored size: 1.32 KB

Contents

# coding: utf-8
module I18n::Tasks::KeyPatternMatching
  extend self
  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(/\{(.*?)}/) { "(#{$1.strip.gsub /\s*,\s*/, '|'})" }
  end

  def key_match_pattern(k)
    @key_match_pattern ||= {}
    @key_match_pattern[k] ||= begin
      "#{k.gsub(KEY_INTERPOLATION_RE, ':')}#{':' if k.end_with?('.')}"
    end
  end

  # @return true if the key looks like an expression
  KEY_INTERPOLATION_RE = /(?:\#{.*?}|\*+|\:+)/.freeze
  def key_expression?(k)
    @key_is_expr ||= {}
    if @key_is_expr[k].nil?
      @key_is_expr[k] = (k =~ KEY_INTERPOLATION_RE || k.end_with?('.'))
    end
    @key_is_expr[k]
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
i18n-tasks-0.8.7 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.8.6 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.8.5 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.8.4 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.8.3 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.8.2 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.8.1 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.8.0 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.13 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.12 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.11 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.10 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.9 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.8 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.7 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.6 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.7.5 lib/i18n/tasks/key_pattern_matching.rb