acts_as_taggable with different language tags

As part of my Rails project I needed to tag items in Chinese and in English. For obvious reasons I wanted to use the acts_as_taggable plugin (not the gem). I really like the way it works. It is very clean and elegant solution for tagging.

However my problem was how do I distinguish a Chinese tag from an English tag. I came up with a few solutions. One being to use the geotagging formula which would translate to Chinese_tag:English_tag. Initially this seemed like a good idea, But, it does seem a bit tied down. What if a user wanted to tag it with an English tag, but not the corresponding Chinese tag ?

So the simple solution I came up with was to add a language field (VARCHAR) to the tag database. If it was a Chinese tag I would simply put ‘ch’ in the language and if it was English I would simply put ‘en’

Here is the actual change I made to the plugin :


def tag_with(list, lang)
  Tag.transaction do
    taggings.destroy_all
    Tag.parse(list).each do |name|
      if acts_as_taggable_options[:from]
         send(acts_as_taggable_options[:from]).tags.find_or_create_by_name(name).on(self) 
      else
        begin
          tag_find = Tag.find_by_name_and_language(name,lang).on(self) 
        rescue
          Tag.create(:name => name, :language =>lang).on(self) 
        end
      end 
    end 
  end 
end

As you can see this method takes an extra parameter ‘lang’. The change has been made in the else statement. It tries to find the tag with the language. If that fails then it creates the tag. This replaced a simple Tag.find_or_create_by_name(name).on(self)Its as simple as that. The tag_with method now accepts and saves the language field.

I also implemented these methods which are self explanatory :


 def tag_chinese_list
    tags.collect {|tag| tag.name.include?(" ") ? "'#{tag.name}'" : tag.name if tag.language =="ch" }.join(" ") }
end

The above method simply retrieves all of the Chinese tags. I have a similar one for English. I also added a find_tagged_with_chinese method. This is just a copy of the original find_tagged_with method with an extra AND language =”ch” at the end.

I should really re-factor the code. For example making the tag_list take a language parameter.

I hope this helps someone.

Hamza

Sorry, comments are closed for this article.