diff --git a/app/models/concerns/taggable.rb b/app/models/concerns/taggable.rb index fb7eefb50..31f81e709 100644 --- a/app/models/concerns/taggable.rb +++ b/app/models/concerns/taggable.rb @@ -27,14 +27,28 @@ def tag_list all_tags.uniq.sort end + # Builds a hash where the keys are the tags and the values are the number of + # their occurrences + # + # @return [Hash Integer>] def tag_cloud - Hash[all_tags.group_by(&:to_s).map { |k, v| [k, v.size] }.sort] + Hash[ + all_tags + .group_by(&:to_s) + .map { |tag_name, values| [tag_name, values.size] } + .sort_by { |array| array.first.downcase } + ] end def find_like_tag(pattern) all_tags.uniq.select { |t| t =~ /#{pattern}/i } end + # Builds a hash where the keys are the capital letters of the tags and the + # values are the individual tags together with the number of their + # occurrences + # + # @return [Hash>>] def alphabetical_grouped_tags tag_cloud.group_by { |tag_name, _| tag_name[0].capitalize } end diff --git a/spec/models/taggable_spec.rb b/spec/models/taggable_spec.rb index b8ae50a08..771b7a04e 100644 --- a/spec/models/taggable_spec.rb +++ b/spec/models/taggable_spec.rb @@ -1,18 +1,27 @@ require 'spec_helper' describe Taggable do - let (:tags) { %w(foo bar baz) } - let (:more_tags) { %w(foo baz qux) } - let (:organization) { Fabricate(:organization) } - let! (:offer) { Fabricate(:offer, - organization: organization, - tags: tags) } - let! (:another_offer) { Fabricate(:offer, - organization: organization, - tags: more_tags) } + let(:organization) { Fabricate(:organization) } + let!(:offer) do + Fabricate( + :offer, + organization: organization, + tags: tags + ) + end + let!(:another_offer) do + Fabricate( + :offer, + organization: organization, + tags: more_tags + ) + end context "class methods and scopes" do + let(:tags) { %w(foo bar baz) } + let(:more_tags) { %w(foo baz qux) } + it "tagged_with" do expect(Offer.tagged_with("bar")).to eq [offer] end @@ -26,12 +35,17 @@ expect(Offer.find_like_tag("Foo")).to eq ["foo"] expect(Offer.find_like_tag("none")).to eq [] end + end + + describe '.alphabetical_grouped_tags' do + let(:tags) { %w(foo bar baz Boo) } + let(:more_tags) { %w(foo baz qux) } - it "alphabetical_grouped_tags" do + it 'sorts them by alphabetical order case insensitive' do expect(Offer.alphabetical_grouped_tags).to eq({ - "B" => [["bar", 1], ["baz", 2]], - "F" => [["foo", 2]], - "Q" => [["qux", 1]] + 'B' => [['bar', 1], ['baz', 2], ['Boo', 1]], + 'F' => [['foo', 2]], + 'Q' => [['qux', 1]] }) end end