Sha256: 095d7ba9c95e6b593cfdfebf31080c2a87875a28508113b03a39d56ba0f3c148

Contents?: true

Size: 1.31 KB

Versions: 7

Compression:

Stored size: 1.31 KB

Contents

# coding: utf-8
module I18n::Tasks::KeyPatternMatching
  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

7 entries across 7 versions & 1 rubygems

Version Path
i18n-tasks-0.6.1 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.6.0 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.5.4 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.5.3 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.5.2 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.5.1 lib/i18n/tasks/key_pattern_matching.rb
i18n-tasks-0.5.0 lib/i18n/tasks/key_pattern_matching.rb