Module: Sluggable

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

Instance Method Summary collapse

Instance Method Details

#append_suffix(str, count) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/dude_its_sluggable.rb', line 35

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



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

def generate_slug!
  the_slug = to_slug(value_to_slug)
  obj = self.class.find_by(slug: the_slug)
  count = 2
  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



8
9
10
# File 'lib/dude_its_sluggable.rb', line 8

def to_param
  self.slug
end

#to_slug(name) ⇒ Object



28
29
30
31
32
33
# File 'lib/dude_its_sluggable.rb', line 28

def to_slug(name)
  str = name.strip
  str.gsub!(/\s*[^A-Za-z0-9]\s*/, "-")
  str.gsub!(/-+/, "-")
  str.downcase
end

#value_to_slugObject



24
25
26
# File 'lib/dude_its_sluggable.rb', line 24

def value_to_slug
  fail NotImplementedError, "Abstract method: defined by targeted subclass."
end