From 7671606ddcd0e16f1b31dd8e71635913771ed127 Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Wed, 20 Jun 2018 20:32:28 +0200 Subject: [PATCH] Add `Formatter::enumeration`. --- Library/Homebrew/test/formatter_spec.rb | 18 ++++++++++++++++++ Library/Homebrew/utils/formatter.rb | 7 +++++++ 2 files changed, 25 insertions(+) diff --git a/Library/Homebrew/test/formatter_spec.rb b/Library/Homebrew/test/formatter_spec.rb index 14c63b8c3a..8d5ca8f41a 100644 --- a/Library/Homebrew/test/formatter_spec.rb +++ b/Library/Homebrew/test/formatter_spec.rb @@ -76,4 +76,22 @@ describe Formatter do expect(described_class.pluralize(2, "new formula")).to eq("2 new formulae") end end + + describe "::enumeration" do + it "returns nil if given no arguments" do + expect(described_class.enumeration).to be nil + end + + it "returns the input as string if there is only one argument" do + expect(described_class.enumeration(1)).to eq("1") + end + + it "concatenates two items with “and”" do + expect(described_class.enumeration(1, 2)).to eq("1 and 2") + end + + it "concatenates all items with a comma and appends the last with “and”" do + expect(described_class.enumeration(1, 2, 3)).to eq("1, 2 and 3") + end + end end diff --git a/Library/Homebrew/utils/formatter.rb b/Library/Homebrew/utils/formatter.rb index ec144bf2f8..e6bdf6f034 100644 --- a/Library/Homebrew/utils/formatter.rb +++ b/Library/Homebrew/utils/formatter.rb @@ -108,4 +108,11 @@ module Formatter show_count ? "#{count} #{words}" : words end + + def enumeration(*items) + *items, last = items.map(&:to_s) + return last if items.empty? + + "#{items.join(", ")} and #{last}" + end end