Sha256: 816472180a1aed68256b45fb0cbde66d8b1a490cd8faec4d181f7fb1dc454032

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

module Mongoid
  module TagCollectible
    class Tag
      include Mongoid::Document
      include Mongoid::Timestamps

      field :name, type: String
      index({ name: 1 }, { unique: true })

      field :count, type: Integer, default: 0
      index({ count: -1 })

      before_destroy :_remove_tags!
      before_update :_rename_tag!
      attr_accessor :renaming

      def renaming?
        !! renaming
      end

      def tagged
        tagged_class.where(tags: self.name)
      end

      def _remove_tags!
        tagged_class.remove_tag!(self[:name]) unless renaming?
      end

      def self.find(value)
        if Moped::BSON::ObjectId.legal?(value)
          super(value)
        else
          where(name: value).first
        end
      end

      private

      def _rename_tag!
        if ! new_record? && name_changed?
          self.class.where(name: name).each do |tag|
            tag.renaming = true
            tag.destroy
          end
          tagged_class.rename_tag!(name_was, name)
        end
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-tag-collectible-0.1.0 lib/mongoid-tag-collectible/tag.rb