开发者

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_ tagg开发者_StackOverflow社区able_on takes over and saves the tag list?

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

Thanks

Simon


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


You can add the following line:

ActsAsTaggableOn.force_parameterize = true

to an initializer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜