Module: Mongoid::Taggable::ClassMethods

Defined in:
lib/mongoid/taggable.rb

Instance Method Summary collapse

Instance Method Details

#disable_tags_index!Object



57
58
59
# File 'lib/mongoid/taggable.rb', line 57

def disable_tags_index!
  @do_tags_index = false
end

#enable_tags_index!Object



61
62
63
# File 'lib/mongoid/taggable.rb', line 61

def enable_tags_index!
  @do_tags_index = true
end

#save_tags_index!Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/mongoid/taggable.rb', line 78

def save_tags_index!
  return unless @do_tags_index

  map = "function() {
    if (!this.tags_array) {
      return;
    }

    for (index in this.tags_array) {
      emit(this.tags_array[index], 1);
    }
  }"

  reduce = "function(previous, current) {
    var count = 0;

    for (index in current) {
      count += current[index]
    }

    return count;
  }"

  # Since map_reduce is normally lazy-executed, call 'raw'
  # Should not be influenced by scoping. Let consumers worry about
  # removing tags they wish not to appear in index.
  self.unscoped.map_reduce(map, reduce).out(replace: tags_index_collection_name).raw
end

#tagged_with(tag) ⇒ Object

returns an array of distinct ordered list of tags defined in all documents



35
36
37
# File 'lib/mongoid/taggable.rb', line 35

def tagged_with(tag)
  self.any_in(:tags_array => [tag])
end

#tagged_with_all(*tags) ⇒ Object



39
40
41
# File 'lib/mongoid/taggable.rb', line 39

def tagged_with_all(*tags)
  self.all_in(:tags_array => tags.flatten)
end

#tagged_with_any(*tags) ⇒ Object



43
44
45
# File 'lib/mongoid/taggable.rb', line 43

def tagged_with_any(*tags)
  self.any_in(:tags_array => tags.flatten)
end

#tagsObject



47
48
49
# File 'lib/mongoid/taggable.rb', line 47

def tags
  tags_index_collection.find.to_a.map{ |r| r["_id"] }
end

#tags_index_collectionObject



74
75
76
# File 'lib/mongoid/taggable.rb', line 74

def tags_index_collection
  @tags_index_collection ||= Moped::Collection.new(self.collection.database, tags_index_collection_name)
end

#tags_index_collection_nameObject



70
71
72
# File 'lib/mongoid/taggable.rb', line 70

def tags_index_collection_name
  "#{collection_name}_tags_index"
end

#tags_separator(separator = nil) ⇒ Object



65
66
67
68
# File 'lib/mongoid/taggable.rb', line 65

def tags_separator(separator = nil)
  @tags_separator = separator if separator
  @tags_separator || ','
end

#tags_with_weightObject

retrieve the list of tags with weight (i.e. count), this is useful for creating tag clouds



53
54
55
# File 'lib/mongoid/taggable.rb', line 53

def tags_with_weight
  tags_index_collection.find.to_a.map{ |r| [r["_id"], r["value"]] }
end