Method: MusicBox::Group#search

Defined in:
lib/musicbox/group.rb

#search(query:, fields:, limit: nil) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/musicbox/group.rb', line 49

def search(query:, fields:, limit: nil)
  found = []
  words = [query].flatten.join(' ').tokenize.sort.uniq - ['-']
  words.each do |word|
    regexp = Regexp.new(Regexp.quote(word), true)
    found += @items.values.select do |item|
      fields.find do |field|
        case (value = item.send(field))
        when Array
          value.find { |v| v.to_s =~ regexp }
        else
          value.to_s =~ regexp
        end
      end
    end
  end
  found = found.flatten.compact.uniq
  found = found[0..limit - 1] if limit
  found
end