Class: WulffeldSlug::PrepareString

Inherits:
Object
  • Object
show all
Defined in:
lib/wulffeld_slug/prepare_string.rb

Constant Summary collapse

VALID_WORD_REGEX =
/^[\sa-zA-Z0-9-]+$/i

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(words, options = {}) ⇒ PrepareString

Returns a new instance of PrepareString.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/wulffeld_slug/prepare_string.rb', line 9

def initialize(words, options = {})
  # Original words. Will not be touched.
  @words             = [*words]
  
  # Converted words.
  @slug_words        = []
  
  @options           = options
  @options[:max]   ||= 239
  @options[:case]  ||= :downcase
  @options[:kinds] ||= [:latin, :danish, :norwegian, :german, :swedish, :spanish, :russian, :bulgarian, :cyrillic, :greek, :macedonian, :romanian, :serbian, :ukrainian]
  
  @slug              = ''
  
  prepare_string
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



3
4
5
# File 'lib/wulffeld_slug/prepare_string.rb', line 3

def options
  @options
end

#slugObject

Returns the value of attribute slug.



3
4
5
# File 'lib/wulffeld_slug/prepare_string.rb', line 3

def slug
  @slug
end

#wordsObject

Returns the value of attribute words.



3
4
5
# File 'lib/wulffeld_slug/prepare_string.rb', line 3

def words
  @words
end

Instance Method Details

#prepare_stringObject



28
29
30
31
32
# File 'lib/wulffeld_slug/prepare_string.rb', line 28

def prepare_string
  prepare_words
  prepare_case
  combine_words
end

#prepare_word(word) ⇒ Object



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/wulffeld_slug/prepare_string.rb', line 34

def prepare_word(word)
  word = word.dup
  # Blow away apostrophes
  word.gsub! /['`ยด]/, ''

  # @ --> at, and & --> and
  word.gsub! /\s*@\s*/, " at "
  word.gsub! /\s*&\s*/, " and "

  # First see if transliteration produces something worthwhile.
  options[:kinds].each do |kind|
    w = Babosa::Identifier.new(word).transliterate!(kind)
    if w =~ VALID_WORD_REGEX && word.length - w.length < 10
      word = w
      break
    end
  end

  # More brutality needed.
  if word !~ VALID_WORD_REGEX
    potential = []
    options[:kinds].each do |kind|
      potential << Babosa::Identifier.new(word).transliterate!(kind).gsub(/[^\sa-zA-Z0-9]+/i, '-').split('-').map(&:strip).reject(&:blank?).join('-')
    end
    
    potential.sort {|a,b| b.length <=> a.length }.each do |w|
      if w =~ VALID_WORD_REGEX
        word = w
        break
      end
    end
  end

  word.strip!

  # Convert spaces to dashes.
  word.gsub!(/[\s]+/i, '-')

  # Remove non-alpha/num.
  word.gsub!(/[^a-zA-Z0-9-]+/i, '')

  # Remove dashes at start and end of word.
  word.gsub!(/^\-+/, '')
  word.gsub!(/\-+$/, '')

  @slug_words << word unless word.blank?
end