ruby-on-railsacts-as-taggable

Hyphenate tags added to acts_as_taggable_on


I am using acts_ as_ taggable_on in my app and have it working perfectly however I am looking for information on how to make one modification.

At present if I enter a tag which includes spaces, the tag is saved with these spaces and so to view all records with this tag I have something like:

http://myapp.local/tag/this%20tag%20has%20spaces

How can I hyphenate tags when they are first saved by acts_ as_ taggable_on so that the tag is stored as this-tag-has-spaces?

I can substitute the values as follows, but how do I do this before acts_ as_ taggable_on takes over and saves the tag list?

tag.downcase.gsub(/[^[:alnum:]]/,'-').gsub(/-{2,}/,'-')

Thanks

Simon


Solution

  • By taking advantage of the fact that acts_as_taggable_on_steroids exposes a tag_list accessor that can be written to, here is what I did on one of my models. I assume you could do something similar:

    class MyTaggableObject < ActiveRecord::Base 
      acts_as_taggable
    
      before_validation :clean_up_tags
    
      # Clean up tag formatting
      def clean_up_tags
        # Make lowercase 
        self.tag_list.map!(&:downcase) 
    
        # Replace any non-word ([^\w]) characters with a hyphen
        self.tag_list.map! {|tag| tag.gsub(/[^\w]+/i,'-')} 
      end
    end