Class: I15R::PatternMatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/i15r/pattern_matcher.rb

Defined Under Namespace

Classes: ErbTransformer, HamlTransformer, Transformer

Constant Summary collapse

HAML_SYMBOLS =
["%", "#", "{", "}", "(", ")", ".", "_", "-"]
PATTERNS =
{
  :erb => [
    /<%=\s*link_to\s+(?<title>['"].+?['"])/,
    /<%=.*label(_tag)?[^,]+?(?<label-title>(['"].+?['"]|:[[:alnum:]_]+))[^,]+%>.*$/,
    /<%=.*label(_tag)?.*?,\s*(?<label-title>(['"].+?['"]|:[[:alnum:]_]+))/,
    /<%=.*submit(_tag)?\s+(?<submit-text>(['"].+?['"]|:[[:alnum:]_]+))/,
    />(?<tag-content>[[:space:][:alnum:][:punct:]]+?)<\//,
    /<a\s+title=['"](?<link-title>.+?)['"]/,
    /^\s*(?<pre-tag-text>[[:alnum:]]+[[:alnum:][:space:][:punct:]]*?)</
  ],
  :haml => [
    /=.*link_to\s+(?<title>['"].+?['"]),/,
    /=.*label(_tag)?[^,]+?(?<label-title>(['"].+?['"]|:[[:alnum:]_]+))[^,]*$/,
    /=.*label(_tag)?.*?,\s*(?<label-title>(['"].+?['"]|:[[:alnum:]_]+))/,
    /=.*submit(_tag)?\s+(?<submit-text>(['"].+?['"]|:[[:alnum:]_]+))/,
    %r{^\s*(?<content>[[:space:][:alnum:]'/(),]+)$},
    %r{^\s*[[#{HAML_SYMBOLS.join('')}][:alnum:]]+?\{.+?\}\s+(?<content>.+)$},
    %r{^\s*[[#{HAML_SYMBOLS.join('')}][:alnum:]]+?\(.+?\)\s+(?<content>.+)$},
    %r{^\s*[[#{(HAML_SYMBOLS - ['{', '}', '(', ')']).join('')}][:alnum:]]+?\s+(?<content>.+)$}
  ]
}

Instance Method Summary collapse

Constructor Details

#initialize(prefix, file_type, options = {}) ⇒ PatternMatcher

Returns a new instance of PatternMatcher.



26
27
28
29
30
31
# File 'lib/i15r/pattern_matcher.rb', line 26

def initialize(prefix, file_type, options={})
  @prefix = prefix
  @file_type = file_type
  transformer_class = self.class.const_get("#{file_type.to_s.capitalize}Transformer")
  @transformer = transformer_class.new(options[:add_default])
end

Instance Method Details

#run(text) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/i15r/pattern_matcher.rb', line 40

def run(text)
  lines = text.split("\n")
  new_lines = lines.map do |line|
    new_line = line
    PATTERNS[@file_type].detect do |pattern|
      if m = pattern.match(line)
        m.names.each do |group_name|
          if /\w/.match(m[group_name])
            new_line = @transformer.transform(m, m[group_name], line, translation_key(m[group_name]))
          end
        end
      end
    end
    if block_given? and line != new_line
      yield line, new_line
    end
    new_line
  end
  new_lines.join("\n")
end

#translation_key(text) ⇒ Object



33
34
35
36
37
38
# File 'lib/i15r/pattern_matcher.rb', line 33

def translation_key(text)
  #TODO: downcase does not work properly for accented chars, like 'Ú', see function in ActiveSupport that deals with this
  #TODO: [:punct:] would be nice but it includes _ which we don't want to remove
  key = text.strip.downcase.gsub(/[\s\/]+/, '_').gsub(/[!?.,:"';()#\/\\]/, '')
  "#{@prefix}.#{key}"
end