Module: SlugableDanielTest

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

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#generate_slugObject



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

def generate_slug
  self.slug = slug_uniqueize( self, options: { column_name: self.class.slug_column.to_sym, count: -1 }) 
end

#generate_slug_prefix(obj, column_name) ⇒ Object



27
28
29
30
# File 'lib/slugable_daniel_test.rb', line 27

def generate_slug_prefix(obj, column_name)    
  #obj[column_name].gsub(/\W/," ").split.join("-").downcase      
  obj[column_name].gsub(/\s*[^A-Za-z0-9]\s*/," ").split.join("-").downcase      
end

#generate_slug_suffix(count) ⇒ Object



23
24
25
# File 'lib/slugable_daniel_test.rb', line 23

def generate_slug_suffix(count)
  (count + 1) == 0 ? "" : "-"+(count + 1).to_s   
end

#slug_uniqueize(obj, options: {}) ⇒ Object



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

def slug_uniqueize(obj, options: {} )    
   the_slug = generate_slug_prefix(obj, options[:column_name]) + generate_slug_suffix(options[:count])
    record = obj.class.find_by slug: the_slug      
    if record && record != obj # the_slug has already been used by the others.
       options[:count] += 1          
       return slug_uniqueize(obj, options: options)    
    end  
    the_slug
end