diff --git a/CHANGELOG.md b/CHANGELOG.md index 938b79437..331e850e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,10 @@ As such, a _Feature_ would map to either major or minor. A _bug fix_ to a patch. * Performance * Misc +### Master [changes](https://github.com/mbleigh/acts-as-taggable-on/compare/v3.3.0...v3.4.0) + + * Features + * [@damzcodes #577 Popular feature](https://github.com/mbleigh/acts-as-taggable-on/pull/577) ### [3.3.0 / 2014-07-08](https://github.com/mbleigh/acts-as-taggable-on/compare/v3.2.6...v3.3.0) diff --git a/README.md b/README.md index 2a7cb175c..4fc8c4d98 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,22 @@ end @user.tag_list # => ["north", "east", "south", "west"] ``` +### Finding most or least used tags + +You can find the most or least used tags by using: + +```ruby +User.most_used +User.least_used +``` + +You can also filter the results by passing the method a limit, however the default limit is 50. + +```ruby +User.most_used(10) +User.least_most(10) +``` + ### Finding Tagged Objects Acts As Taggable On uses scopes to create an association for tags. @@ -201,6 +217,7 @@ You can also use `:wild => true` option along with `:any` or `:exclude` option. __Tip:__ `User.tagged_with([])` or `User.tagged_with('')` will return `[]`, an empty set of records. + ### Relationships You can find objects of the same type based on similar tags on certain contexts. diff --git a/lib/acts_as_taggable_on/tag.rb b/lib/acts_as_taggable_on/tag.rb index e9e49f633..f65358c7e 100644 --- a/lib/acts_as_taggable_on/tag.rb +++ b/lib/acts_as_taggable_on/tag.rb @@ -20,6 +20,8 @@ def validates_name_uniqueness? end ### SCOPES: + scope :most_used, ->(limit = 20) { order('taggings_count desc').limit(limit) } + scope :least_used, ->(limit = 20) { order(:taggings_count).limit(limit) } def self.named(name) if ActsAsTaggableOn.strict_case_match @@ -101,6 +103,9 @@ def count end class << self + + + private def comparable_name(str) diff --git a/spec/acts_as_taggable_on/tag_spec.rb b/spec/acts_as_taggable_on/tag_spec.rb index 0923c8005..2ceabad16 100644 --- a/spec/acts_as_taggable_on/tag_spec.rb +++ b/spec/acts_as_taggable_on/tag_spec.rb @@ -286,4 +286,24 @@ end end end + + describe 'popular tags' do + before do + %w(sports rails linux tennis golden_syrup).each_with_index do |t, i| + tag = ActsAsTaggableOn::Tag.new(name: t) + tag.taggings_count = i + tag.save! + end + end + + it 'should find the most popular tags' do + expect(ActsAsTaggableOn::Tag.most_used(3).first.name).to eq("golden_syrup") + expect(ActsAsTaggableOn::Tag.most_used(3).length).to eq(3) + end + + it 'should find the least popular tags' do + expect(ActsAsTaggableOn::Tag.least_used(3).first.name).to eq("sports") + expect(ActsAsTaggableOn::Tag.least_used(3).length).to eq(3) + end + end end