Module: SearchKeyHelper

Included in:
Kakimasu::KeysController
Defined in:
app/helpers/search_key_helper.rb

Overview

Sets translation key for lazy lookup or unsets it.

Instance Method Summary collapse

Instance Method Details

#lazy_lookup_key(key, path) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/helpers/search_key_helper.rb', line 3

def lazy_lookup_key(key, path)
  path = 'app/views/' + path
  file = File.read(path)

  matches = Array.new           #All places where this key is used in given file
  locations = Array.new         #Indexes which determines where to make changes
  file_length_differential = 0  #File length difference because substitutions will change file size.

  # Finds all places where given translation key is used
  file.scan(/[=|\s][t][\s]*[(]?[\s]*['|:]#{key}/) do |c|
    matches.push [c, $~.offset(0)[0]]
  end

  matches.each do |array|
    if array.first.match /[=|\s][t][\s]*[(]?[\s]*[:]\w*/  # if translation written with : not '' then its special case
      # Key with ':key' is sustituted with "'.key'"
      index = array.first.index(/:#{key}/)
      file.slice!(array.last + index + file_length_differential, (":#{key}").length)
      file.insert(array.last + index + file_length_differential, "'.#{key}'")
      file_length_differential += ("'.#{key}'").length - (":#{key}").length
    elsif key[0] != '.'
      index = array.first.index(key)
      locations.push array.last + index + file_length_differential
    end
  end

  # Insert '.' just before key for lazy lookup
  locations.each_with_index do |location, index|
    file.insert(location + index, '.')
  end

  File.write(path, file)
end

#remove_lazy_lookup(key, path) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'app/helpers/search_key_helper.rb', line 37

def remove_lazy_lookup(key, path)
  path = 'app/views/' + path
  file = File.read(path)

  # Get rid of prefix of has lazy lookup prefix
  if key.include? '.'
    key = key.split('.').last
    key.prepend '.'
  end

  matches = Array.new    # All places where given key is used in file
  locations = Array.new  #Indexes which determintes where to make changes

  key.slice! 0 if key[0] == '.'
  file.scan(/[=|\s][t][\s]*[(]?[\s]*['][.]#{key}/) do |c|
    matches.push [c, $~.offset(0)[0]]
  end

  matches.each do |array|
    index = array.first.index('.' + key)
    locations.push array.last + index
  end

  locations.each_with_index do |location, index|
    file.slice!(location - index)    # Removes '.' from match
  end

  File.write(path, file)
end