Skip to content

Instantly share code, notes, and snippets.

@JakubOboza
Created November 22, 2011 15:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JakubOboza/1385866 to your computer and use it in GitHub Desktop.
Save JakubOboza/1385866 to your computer and use it in GitHub Desktop.
tags formongoid collections.
module Mongoid
module Document
module Taggable
def self.included(base)
base.class_eval do |base_document|
base_document.field :tags, :type => Array, :default => []
base_document.index :tags
include InstanceMethods
extend ClassMethods
end
end
module InstanceMethods
def tag_list=(tags)
if tags.is_a?(Array)
self.tags = tags.compact
else
self.tags = tags.split(",").collect{ |t| t.strip }.delete_if{ |t| t.blank? }
end
end
def tag_list
self.tags.join(", ") if tags
end
def has_tags?( tags_to_check )
tags_to_check = tags_to_check.split(",") unless tags_to_check.is_a?(Array)
tags_to_check = tags_to_check.map(&:strip)
return true if self.tags.sort & tags_to_check.sort == tags_to_check.sort
false
end
end
module ClassMethods
def tags
all.only(:tags).collect{ |ms| ms.tags }.flatten.uniq.compact
end
def tagged_with(_tags)
_tags = [_tags] unless _tags.is_a? Array
criteria.in(:tags => _tags).to_a
end
end
end
end
end
module Mongoid
module Document
module Taggable
module Whitelist
def self.included(base)
base.class_eval do |document|
alias_method :"not_white_listed_tags=", :"tag_list="
include InstanceMethods
end
end
module InstanceMethods
def tag_list=(tags)
if self.method(:"white_tag?")
filtered_tags = tags.split(",").collect{ |t| t.strip }.delete_if do |t|
!self.white_tag?(t)
end
self.not_white_listed_tags=(filtered_tags)
else
self.not_white_listed_tags=(tags)
end
end
end
end
end
end
end
# initial simple test case.
require 'spec_helper'
class TestTags
include Mongoid::Document
include Mongoid::Document::Taggable
end
describe "Tags" do
before(:each) do
@test_tags = TestTags.new
end
it "should build testtag object and save it without any problems" do
@test_tags.tag_list.should be_empty
@test_tags.tag_list.should_not be_nil
end
it "should be able to add tags, save them and load" do
@test_tags.tag_list = "jakub, kuba, michal, kuba, jakub"
["kuba", "jakub", "michal"].map{|tag| @test_tags.tag_list.should be_include(tag) }
@test_tags.save
@test_tags.reload
["kuba", "jakub", "michal"].map{|tag| @test_tags.tag_list.should be_include(tag) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment