Sha256: 4b9151315f6c244aadfc525d103d01af996be2fe6cd2f0ddcad89f56ec1a3807

Contents?: true

Size: 1.42 KB

Versions: 2

Compression:

Stored size: 1.42 KB

Contents

module Gamefic
  module Matchable
    SPLIT_REGEXP = /[\s]+/

    # Get an array of keywords associated with this object.
    # The default implementation splits the value of self.to_s into an array.
    #
    # @return [Array<String>]
    def keywords
      self.to_s.downcase.split(SPLIT_REGEXP).uniq
    end

    # Determine if this object matches the provided description.
    # In a regular match, every word in the description must be a keyword.
    # Fuzzy matches accept words if a keyword starts with it, e.g., "red"
    # would be a fuzzy match for "reddish."
    #
    # @example
    #   dog = "big red dog"
    #   dog.extend Gamefic::Matchable
    #
    #   dog.match?("red dog")  #=> true
    #   dog.match?("gray dog") #=> false
    #   dog.match?("red do")   #=> false
    #
    #   dog.match?("re do", fuzzy: true)  #=> true
    #   dog.match?("red og", fuzzy: true) #=> false
    #
    # @return [Boolean]
    def match? description, fuzzy: false
      words = description.split(SPLIT_REGEXP)
      return false if words.empty?
      matches = 0
      available = keywords
      words.each { |w|
        if fuzzy
          available.each { |k|
            if k.gsub(/[^a-z0-9]/, '').start_with?(w.downcase.gsub(/[^a-z0-9]/, ''))
              matches +=1
              break
            end
          }
        else
          matches +=1 if available.include?(w.downcase)
        end
      }
      matches == words.length
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
gamefic-1.7.0 lib/gamefic/matchable.rb
gamefic-1.6.0 lib/gamefic/matchable.rb