Add Searchable helper module.

This commit is contained in:
Markus Reiter 2018-06-05 14:21:05 +02:00
parent 6fcc5d14de
commit 46e0de1762
2 changed files with 61 additions and 0 deletions

View File

@ -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

View File

@ -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