Method: Packr::Base62#encode

Defined in:
lib/packr/base62.rb

#encode(script) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
# File 'lib/packr/base62.rb', line 16

def encode(script)
  words = search(script)
  words.sort!
  
  encoded = Collection.new # a dictionary of base62 -> base10
  words.size.times { |i| encoded.put(Packr.encode62(i), i) }
  
  replacement = lambda { |word| words.get(word).replacement }
  
  index = 0
  words.each do |word, key|
    if encoded.has?(word)
      word.index = encoded.get(word)
      def word.to_s; ""; end
    else
      index += 1 while words.has?(Packr.encode62(index))
      word.index = index
      index += 1
      if word.count == 1
        def word.to_s; ""; end
      end
    end
    word.replacement = Packr.encode62(word.index)
    if word.replacement.length == word.to_s.length
      def word.to_s; ""; end
    end
  end
  
  # sort by encoding
  words.sort! { |word1, word2| word1.index - word2.index }
  
  # trim unencoded words
  words = words.slice(0, get_key_words(words).split("|").length)
  
  script = script.gsub(get_pattern(words), &replacement)
  
  # build the packed script
  
  p = escape(script)
  a = "[]"
  c = get_count(words)
  k = get_key_words(words)
  e = get_encoder(words)
  d = get_decoder(words)
  
  # the whole thing
  UNPACK.call(p,a,c,k,e,d)
end