Module: Glue::Taggable

Includes:
Og::EntityMixin
Defined in:
lib/glue/taggable.rb

Overview

Add tagging methods to the target class. For more information on the algorithms used surf: www.pui.ch/phred/archives/2005/04/tags-database-schemas.html

Example

class Article

  include Taggable
  ..
end

article.tag(‘navel’, ‘gmosx’, ‘nitro’) article.tags article.tag_names Article.find_with_tags(‘navel’, ‘gmosx’) Article.find_with_any_tag(‘name’, ‘gmosx’)

Tag.find_by_name(‘ruby’).articles

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Og::EntityMixin

#assign_properties, #delete, #force_save!, #insert, #og_clone, #og_quote, #properties_to_hash, #reload, #save, #saved?, #transaction, #update, #update_by_sql, #update_properties

Class Method Details

.included(base) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
# File 'lib/glue/taggable.rb', line 165

def self.included(base)
  Tag.module_eval do
    many_to_many base
  end
  base.extend(ClassMethods)
  #--
  # FIXME: Og should handle this automatically.
  #++
  base.send :include, Aspects
  base.before 'tags.clear', :on => [:og_delete]
end

.tags_to_names(the_tags, separator = Taggable.separator) ⇒ Object

Helper.



179
180
181
182
183
184
185
186
187
188
189
# File 'lib/glue/taggable.rb', line 179

def self.tags_to_names(the_tags, separator = Taggable.separator)
  if the_tags.is_a? Array
    names = the_tags 
  elsif the_tags.is_a? String
    names = the_tags.split(separator)
  end
  
  names = names.flatten.uniq.compact
  
  return names
end

Instance Method Details

#tag(the_tags, options = {}) ⇒ Object Also known as: tag!

Add a tag for this object.



85
86
87
88
89
90
91
92
93
94
95
# File 'lib/glue/taggable.rb', line 85

def tag(the_tags, options = {})
  options = {
    :clear => true
  }.merge(options)
    
  self.tags.clear if options[:clear]
  
  for name in Taggable.tags_to_names(the_tags)
    Tag.find_or_create_by_name(name).tag(self) unless self.tagged_with?(name)
  end    
end

#tag_namesObject

Return the names of the tags.



100
101
102
# File 'lib/glue/taggable.rb', line 100

def tag_names
  tags.collect { |t| t.name }
end

#tag_string(separator = Taggable.separator) ⇒ Object

Return the tag string



106
107
108
# File 'lib/glue/taggable.rb', line 106

def tag_string(separator = Taggable.separator)
  tags.collect { |t| t.name }.join(separator)    
end

#tagged_with?(tag_name) ⇒ Boolean Also known as: tagged_by?

Checks to see if this object has been tagged with tag_name.

Returns:

  • (Boolean)


113
114
115
# File 'lib/glue/taggable.rb', line 113

def tagged_with?(tag_name)
  tag_names.include?(tag_name)
end