Skip to content

Instantly share code, notes, and snippets.

@Tigraine
Forked from jpemberthy/gist:349242
Created August 10, 2012 11:52
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 Tigraine/3313759 to your computer and use it in GitHub Desktop.
Save Tigraine/3313759 to your computer and use it in GitHub Desktop.
# 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
def self.included(base)
base.class_eval do |base1|
base1.field :tags, :type => Array
base1.index({ tags: 1 })
base1.attr_accessible :tag_list
include InstanceMethods
extend ClassMethods
end
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
@Tigraine
Copy link
Author

Updated for rails 3.2 with it's mass assignment protection.
Also the mongoid index method changed a bit:
https://gist.github.com/3313759

@jpemberthy
Copy link

Cool, haven't work on this in a while :P.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment