Module: Handler

Defined in:
lib/handler.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.generate_handle(title, separator) ⇒ Object

Generate a handle from a string.



62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/handler.rb', line 62

def self.generate_handle(title, separator)
  str = title
  return nil unless str.is_a?(String)
  str = transliterate(str).to_s
  str = str.downcase
  str = str.strip
  str = str.gsub('&', ' and ') # add space for, e.g., "Y&T"
  str = str.delete('.\'"')     # no space
  str = str.gsub(/\W/, ' ')    # space
  str = str.strip
  str = str.gsub(/ +/, separator)
  str
end

.included(base) ⇒ Object

Included hook: extend including class.



6
7
8
# File 'lib/handler.rb', line 6

def self.included(base)
  base.extend ClassMethods
end

.next_handle(handle, separator) ⇒ Object

Get the next handle in the sequence (for avoiding duplicates).



79
80
81
82
83
84
85
# File 'lib/handler.rb', line 79

def self.next_handle(handle, separator)
  if handle =~ /#{separator}\d+$/
    handle.sub(/\d+$/){ |i| i.to_i + 1 }
  else
    handle + separator + "2"
  end
end

.transliterate(string) ⇒ Object

Transliterate a string: change accented Unicode characters to ASCII approximations. Tries several methods, attempting the best first:

  1. unidecode, if installed (rubyforge.org/projects/unidecode)

  2. iconv (included with Ruby, doesn’t work with all Ruby versions)

  3. normalize, then remove un-normalizable characters



18
19
20
21
22
23
# File 'lib/handler.rb', line 18

def self.transliterate(string)
  transliterate_with_unidecode(string) or
    transliterate_with_iconv(string) or
    transliterate_with_normalization(string) or
    string
end

.transliterate_with_iconv(string) ⇒ Object

Transliterate a string with the iconv library. Return nil if unsuccessful (eg, library not available).



42
43
44
45
46
47
48
# File 'lib/handler.rb', line 42

def self.transliterate_with_iconv(string)
  begin
    Iconv.iconv('ascii//ignore//translit', 'utf-8', string).to_s
  rescue
    nil
  end
end

.transliterate_with_normalization(string) ⇒ Object

Transliterate a string using multibyte normalization, then remove remaining non-ASCII characters. Taken from ActiveSupport::Inflector.transliterate.



55
56
57
# File 'lib/handler.rb', line 55

def self.transliterate_with_normalization(string)
  string.mb_chars.normalize.gsub(/[^\x00-\x7F]+/, '').to_s
end

.transliterate_with_unidecode(string) ⇒ Object

Transliterate a string with the unidecode library. Return nil if unsuccessful (eg, library not available).



29
30
31
32
33
34
35
36
# File 'lib/handler.rb', line 29

def self.transliterate_with_unidecode(string)
  begin
    require 'unidecode'
    string.to_ascii
  rescue LoadError
    nil
  end
end