Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/paperclip-strip-strange-characters.rb

Instance Method Summary collapse

Instance Method Details

#strip_strange_characters(ignore = true, hash = true) ⇒ Object



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
36
# File 'lib/paperclip-strip-strange-characters.rb', line 5

def strip_strange_characters(ignore = true, hash = true)
  # Escape str by transliterating to UTF-8 with Iconv
  if ignore
    s = Iconv.iconv('ascii//ignore//translit', 'utf-8', self).to_s
  else
    s = Iconv.iconv('ascii//translit', 'utf-8', self).to_s
  end
  
  # Downcase string
  s.downcase!

  # Remove apostrophes so isn't changes to isnt
  s.gsub!("'", '')

  # Remove quotes 
  s.gsub!("\"", '')

  # Replace any non-letter or non-number character with a space
  s.gsub!(/[^A-Za-z0-9]+/, ' ')

  # Remove spaces from beginning and end of string
  s.strip!

  # Replace groups of spaces with single hyphen
  s.gsub!(/\ +/, '-')
  
  if hash and s == ""
    return Digest::MD5.hexdigest(self) # Fallback - better MD5 than nothing
  end

  return s
end