Class: Vortex::StringUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/vortex_client/string_utils.rb

Overview

String utilities

Class Method Summary collapse

Class Method Details

.create_filename(sentence) ⇒ Object

Turn a normal sentence into a valid, readable filename.

Example:

"A small test" => "a-small-test.html"


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/vortex_client/string_utils.rb', line 15

def self.create_filename(sentence)
  if(sentence.size > 10)then
    truncated_title = sentence.sub(/:.*/,"").sub(/;/,"").sub(/&/,"").sub(/\(/,"").sub(/\)/,"")
    html_filename = self.snake_case(truncated_title)
  else
    html_filename = self.snake_case(sentence)
  end

  # Just keep the 100 first chars, to nearest word.
  if(html_filename.size > 100)then
    html_filename = html_filename.gsub(/\.html$/,"")
    html_filename = html_filename[0..100]
    html_filename = html_filename.gsub(/_[^_]*$/,"") + ".html"
  end
  return html_filename
end

.remove_accents(str) ⇒ Object

Filter accents and some special characters



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/vortex_client/string_utils.rb', line 52

def self.remove_accents(str)
  accents = {
    ['á','à','â','ä','ã','Ã','Ä','Â','À'] => 'a',
    ['é','è','ê','ë','Ë','É','È','Ê'] => 'e',
    ['í','ì','î','ï','I','Î','Ì'] => 'i',
    ['ó','ò','ô','ö','õ','Õ','Ö','Ô','Ò'] => 'o',
    ['œ'] => 'e',
    ['ß'] => 'ss',
    ['ú','ù','û','ü','U','Û','Ù'] => 'u',
    ['æ'] => 'ae',
    ['ø'] => 'o',
    ['å'] => 'a',
    ['Æ'] => 'ae',
    ['Ø'] => 'o',
    ['Å'] => 'a',
    ['§'] => ''
  }
  accents.each do |ac,rep|
    ac.each do |s|
      str.gsub!(s, rep)
    end
  end

  # Remove the rest of the accents and special characters
  conv = Iconv.new("ASCII//TRANSLIT//IGNORE", "UTF-8")
  str = conv.iconv(str)
  return str
end

.snake_case(camel_cased_word_input) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/vortex_client/string_utils.rb', line 32

def self.snake_case(camel_cased_word_input)
  camel_cased_word = camel_cased_word_input + "" # create local copy of string
  camel_cased_word = remove_accents(camel_cased_word)
  camel_cased_word = camel_cased_word.to_s.gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1\2').
    gsub(/([a-z\d])([A-Z])/,'\1\2').downcase

  camel_cased_word = camel_cased_word.to_s.gsub(/ /,'-')
  camel_cased_word = camel_cased_word.to_s.gsub(/^_/,'')
  camel_cased_word = camel_cased_word.gsub("__","_")

  # sanitize the string
  camel_cased_word = camel_cased_word.gsub(/[^a-z._0-9 -]/i, "").
    tr(".", "_").gsub(/(\s+)/, "_").gsub(/_/, '-').downcase
  camel_cased_word = camel_cased_word.to_s.gsub(/--*/,'-')
  return camel_cased_word
end