Skip to content

Instantly share code, notes, and snippets.

@arnklint
Forked from ches/gist:718234
Created August 3, 2011 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnklint/1122573 to your computer and use it in GitHub Desktop.
Save arnklint/1122573 to your computer and use it in GitHub Desktop.
Very simple taggable behavior for Mongoid
# Basic tagging system for mongoid documents.
# jpemberthy 2010
#
# class User
# include Mongoid::Document
# include Mongoid::Document::Taggable
# end
#
# @user = User.new(:name => "Bobby")
# @user.tag_list = "awesome, slick, hefty"
# @user.tags # => ["awesome","slick","hefty"]
# @user.save
#
# User.tagged_with("awesome") # => @user
# User.tagged_with(["slick", "hefty"]) # => @user
#
# @user2 = User.new(:name => "Bubba")
# @user2.tag_list = "slick"
# @user2.save
#
# User.tagged_with("slick") # => [@user, @user2]
module Mongoid
module Document
module Taggable
extend ActiveSupport::Concern
included do
field :tags, :type => Array
index :tags
end
module InstanceMethods
def tag_list=(tags)
self.tags = tags.split(",").collect{ |t| t.strip }.delete_if{ |t| t.blank? }
end
def tag_list
self.tags.join(", ") if tags
end
end
module ClassMethods
# let's return only :tags
def tags
all.only(:tags).collect{ |ms| ms.tags }.flatten.uniq.compact
end
def tagged_like(_perm)
_tags = tags
_tags.delete_if { |t| !t.include?(_perm) }
end
def tagged_with(_tags)
_tags = [_tags] unless _tags.is_a? Array
criteria.in(:tags => _tags).to_a
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment