Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…able_on_steroids@346 20afb1e0-9c0e-0410-9884-91ed27886737
  • Loading branch information
jonathan committed Oct 15, 2007
1 parent d0cad03 commit 0adbf2b
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

* Make find_tagged_with correctly apply :conditions

* Add Tag.destroy_unused option.

[11 October 2007]

* Make tag_counts work correctly with STI.
Expand Down
7 changes: 7 additions & 0 deletions README
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,13 @@ For example, to use spaces instead of commas, add the following to config/enviro

TagList.delimiter = " "

=== Unused tags

Set Tag.destroy_unused to remove tags when they are no longer being
used to tag any objects. Defaults to false.

Tag.destroy_unused = true

=== Other

Problems, comments, and suggestions all welcome. jonathan.viney@gmail.com
3 changes: 3 additions & 0 deletions lib/tag.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ class Tag < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name

cattr_accessor :destroy_unused
self.destroy_unused = false

# LIKE is used for cross-database case-insensitivity
def self.find_or_create_with_like_by_name(name)
find(:first, :conditions => ["name LIKE ?", name]) || create(:name => name)
Expand Down
6 changes: 6 additions & 0 deletions lib/tagging.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
class Tagging < ActiveRecord::Base #:nodoc:
belongs_to :tag
belongs_to :taggable, :polymorphic => true

def after_destroy
if Tag.destroy_unused and tag.taggings.count.zero?
tag.destroy
end
end
end
24 changes: 24 additions & 0 deletions test/acts_as_taggable_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,30 @@ def test_case_insensitivity

assert_equal Post.find_tagged_with("Nature"), Post.find_tagged_with("nature")
end

def test_tag_not_destroyed_when_unused
posts(:jonathan_sky).tag_list.add("Random")
posts(:jonathan_sky).save!

assert_no_difference 'Tag.count' do
posts(:jonathan_sky).tag_list.remove("Random")
posts(:jonathan_sky).save!
end
end

def test_tag_destroyed_when_unused
Tag.destroy_unused = true

posts(:jonathan_sky).tag_list.add("Random")
posts(:jonathan_sky).save!

assert_difference 'Tag.count', -1 do
posts(:jonathan_sky).tag_list.remove("Random")
posts(:jonathan_sky).save!
end
ensure
Tag.destroy_unused = false
end
end

class ActsAsTaggableOnSteroidsFormTest < Test::Unit::TestCase
Expand Down

0 comments on commit 0adbf2b

Please sign in to comment.