From 46e0de1762c8b2b8d5dfaa4953e9b031489a9a6b Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Tue, 5 Jun 2018 14:21:05 +0200 Subject: [PATCH] Add `Searchable` helper module. --- Library/Homebrew/searchable.rb | 31 ++++++++++++++++++++++++ Library/Homebrew/test/searchable_spec.rb | 30 +++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 Library/Homebrew/searchable.rb create mode 100644 Library/Homebrew/test/searchable_spec.rb diff --git a/Library/Homebrew/searchable.rb b/Library/Homebrew/searchable.rb new file mode 100644 index 0000000000..9fca0bfdaa --- /dev/null +++ b/Library/Homebrew/searchable.rb @@ -0,0 +1,31 @@ +module Searchable + def search(string_or_regex, &block) + case string_or_regex + when Regexp + search_regex(string_or_regex, &block) + else + search_string(string_or_regex.to_str, &block) + end + end + + private + + def simplify_string(string) + string.downcase.gsub(/[^a-z\d]/i, "") + end + + def search_regex(regex) + select do |*args| + args = yield(*args) if block_given? + [*args].any? { |arg| arg.match?(regex) } + end + end + + def search_string(string) + simplified_string = simplify_string(string) + select do |*args| + args = yield(*args) if block_given? + [*args].any? { |arg| simplify_string(arg).include?(simplified_string) } + end + end +end diff --git a/Library/Homebrew/test/searchable_spec.rb b/Library/Homebrew/test/searchable_spec.rb new file mode 100644 index 0000000000..aaf2247795 --- /dev/null +++ b/Library/Homebrew/test/searchable_spec.rb @@ -0,0 +1,30 @@ +require "searchable" + +describe Searchable do + subject { ary.extend(described_class) } + + let(:ary) { ["with-dashes"] } + + describe "#search" do + context "when given a block" do + let(:ary) { [["with-dashes", "withdashes"]] } + + it "searches by the selected argument" do + expect(subject.search(/withdashes/) { |_, short_name| short_name }).not_to be_empty + expect(subject.search(/withdashes/) { |long_name, _| long_name }).to be_empty + end + end + + context "when given a regex" do + it "does not simplify strings" do + expect(subject.search(/with\-dashes/)).to eq ["with-dashes"] + end + end + + context "when given a string" do + it "simplifies both the query and searched strings" do + expect(subject.search("with dashes")).to eq ["with-dashes"] + end + end + end +end