Module: Sluggable

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

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#append_suffix(str, count) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/sluggable_knoxjeffrey.rb', line 32

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

#generate_slug!Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/sluggable_knoxjeffrey.rb', line 15

def generate_slug!
  #self.class will be the model that includes the module and slug_column is the
  #class attribute set in the class method
  #therefore self.send will equate to self.title or example is title is the class attribute
  the_slug = to_slug(self.send(self.class.slug_column.to_sym))
  obj = self.class.find_by(slug: the_slug)
  count = 2
  #will keep appending a number if the slug name generated is the same as one already set in the database
  #eg. if "something" is already in the database then it will be something-2, etc
  while obj && obj != self
    the_slug = append_suffix(the_slug, count)
    obj = self.class.find_by slug: the_slug
    count += 1
  end
  self.slug = the_slug.downcase
end

#to_paramObject

changes to_param method to look for slug rather than the default of id



11
12
13
# File 'lib/sluggable_knoxjeffrey.rb', line 11

def to_param
  self.slug
end

#to_slug(name) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/sluggable_knoxjeffrey.rb', line 40

def to_slug(name)
  str = name.strip
  str.gsub!(/\s*[^A-Za-z0-9]\s*/, '-') #replace all non alphnumerics with a -
  str.gsub!(/-+/, '-') #replace consequtive - with a single -
  str.gsub!(/(^-+)|(-+$)/, '') #strip out - at start and end of string
  str.downcase
end