Module: SluggifyThisJs::InstanceMethods

Defined in:
lib/sluggify-this-js.rb

Instance Method Summary collapse

Instance Method Details

#generate_slug(model, attribute) ⇒ Object

Post, self.title



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sluggify-this-js.rb', line 22

def generate_slug(model, attribute)  #Post, self.title
  str = to_slug(attribute)
  count = 2
  obj = model.where(slug: str).first
  while obj && obj != self
    str = str + "-" + count.to_s
    obj = model.where(slug: str).first
    count += 1
  end
  self.slug = str.downcase
end

#to_paramObject



18
19
20
# File 'lib/sluggify-this-js.rb', line 18

def to_param
  self.slug
end

#to_slug(name) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/sluggify-this-js.rb', line 35

def to_slug(name)
  #strip the string
  ret = name.strip

  #blow away apostrophes
  ret.gsub! /['`]/,""

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

  #replace all non alphanumeric with dash
  ret.gsub! /\s*[^A-Za-z0-9]\s*/, '-'

  #convert double dashes to single
  ret.gsub! /-+/,"-"

  #strip off leading/trailing dash
  ret.gsub! /\A[-\.]+|[-\.]+\z/,""

  ret
end