Class: L10nizer::KeyGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/l10nizer/keygen.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeKeyGenerator

Returns a new instance of KeyGenerator.



5
6
7
# File 'lib/l10nizer/keygen.rb', line 5

def initialize
  @seen = {}
end

Instance Attribute Details

#namespaceObject

Returns the value of attribute namespace.



3
4
5
# File 'lib/l10nizer/keygen.rb', line 3

def namespace
  @namespace
end

Instance Method Details

#call(string) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/l10nizer/keygen.rb', line 9

def call(string)
  provisional = [make_safe(namespace), make_safe(string)].compact * "."

  until try(provisional, string)
    match = provisional.match(/_(\d+)$/)
    if match
      provisional.sub! /\d+$/, match[1].to_i.succ.to_s
    else
      provisional << "_1"
    end
  end

  return provisional
end

#make_safe(string) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/l10nizer/keygen.rb', line 33

def make_safe(string)
  return nil if string.nil?
  safe = string.
         downcase.
         gsub(/&[a-z0-9]{1,20};/, ""). # entities
         gsub(/<[^>]*>/, "").          # html
         gsub(/[^a-z0-9]+/, "_").      # non alphanumeric
         slice(0, 40).
         gsub(/^_|_$/, "")             # leading/trailing _
  safe = "unknown" if safe.empty?
  safe
end

#try(key, string) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/l10nizer/keygen.rb', line 24

def try(key, string)
  if [nil, string].include?(@seen[key])
    @seen[key] = string
    true
  else
    false
  end
end