Module: Sluggable

Extended by:
ActiveSupport::Concern
Defined in:
lib/sluggable_austinkim.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#append_suffix(str, count) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/sluggable_austinkim.rb', line 25

def append_suffix(str, count)
  if str.split('-').last.to_i != 0
    str = str.split('-').slice(0...-1).join('-') + '-' + count.to_s
    return str      
  else
    return str + '-' + count.to_s
  end
end

#convert_to_slugObject



34
35
36
37
38
39
# File 'lib/sluggable_austinkim.rb', line 34

def convert_to_slug
  str = self.send(self.class.slug_column.to_sym).strip.downcase
  str.gsub! /[^\da-zA-Z]/, '-'
  str.gsub! /-+/, '-'
  return str
end

#generate_slugObject



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/sluggable_austinkim.rb', line 13

def generate_slug
  the_slug = convert_to_slug
  obj = self.class.find_by(slug: the_slug)
  count = 2
  while obj && obj.slug != self.slug
    the_slug = append_suffix(the_slug, count)
    obj = self.class.find_by(slug: the_slug)
    count += 1
  end
  self.slug = the_slug
end

#to_paramObject



9
10
11
# File 'lib/sluggable_austinkim.rb', line 9

def to_param
  self.slug  
end