Module: Emailer::StringUtilities

Defined in:
lib/emailer/string_utilities.rb

Instance Method Summary collapse

Instance Method Details

#q_char(n) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/emailer/string_utilities.rb', line 10

def q_char(n)
  # We can escape SPACE (0x20) with '_'
  return '_' if n == 32
  
  # We can use ASCII 33 to 126, except '=', '?' and '_' (see above).
  # All other byte values will be encoded with =XX
  (n < 33 || n == 61 || n == 63 || n == 95 || n > 126) ? q_encode_char(n) : n.chr
end

#q_encode_bytes(str) ⇒ Object



19
20
21
# File 'lib/emailer/string_utilities.rb', line 19

def q_encode_bytes(str)
  str.bytes.map { |b| q_char(b) }
end

#q_encode_char(n) ⇒ Object



4
5
6
7
8
# File 'lib/emailer/string_utilities.rb', line 4

def q_encode_char(n)
  hex = n.to_s 16
  hex = "0#{hex}" if hex.length == 1
  "=#{hex}"
end

#q_word(encoding, encoded_str) ⇒ Object



23
24
25
# File 'lib/emailer/string_utilities.rb', line 23

def q_word(encoding, encoded_str)
  "=?#{encoding}?Q?#{encoded_str}?="
end

#split_string(parts, maxlen) ⇒ Object



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

def split_string(parts, maxlen)
  result = ['']
  while parts.length > 0
    if (result[-1].length + parts[0].length <= maxlen)
      result[-1] += parts.shift
    else
      result << parts.shift
    end
  end
  
  result
end

#string_to_q(str) ⇒ Object



27
28
29
30
31
# File 'lib/emailer/string_utilities.rb', line 27

def string_to_q(str)
  max_word_length = 76 - "=?#{str.encoding.to_s}?Q??=".length
  lines = split_string q_encode_bytes(str), max_word_length
  lines.map { |l| q_word(str.encoding.to_s, l) }.join("\r\n ")
end