Sha256: da876e3d2f8ebff469d99a90f61dabfdc632cee4bfbc859ec47e58208a82ad3d

Contents?: true

Size: 1.1 KB

Versions: 62

Compression:

Stored size: 1.1 KB

Contents

module Workarea
  class QueryString
    include GlobalID::Identification

    INVALID_SEARCH_REGEX = /[\]\[:\.;\(\)\{\}^\\\/!~]|<\/?script>|(\s+)?-(\s|$)/

    attr_reader :original
    delegate :present?, :blank?, to: :sanitized

    def self.find(id)
      new(id.humanize(capitalize: false))
    end

    def initialize(original)
      @original = original
    end

    def id
      @id ||= Array(Lingua.stemmer(pieces)).join('_').downcase.gsub(/\W/, '')
    end

    def pieces
      @pieces ||= sanitized.split(/\s/)
    end

    def pretty
      pieces.map(&:downcase).join(' ')
    end

    def phrase?
      pieces.many?
    end

    def sanitized
      @sanitized ||=
        begin
          query = @original
            .to_s
            .gsub(INVALID_SEARCH_REGEX, ' ')
            .strip
            .squeeze(' ')

          query.gsub!('"', '\"') if query.count('"') == 1
          query.gsub!(/(\w)( AND| OR)$/) { "#{::Regexp.last_match(1)}#{::Regexp.last_match(2).downcase}" }

          query
        end
    end

    def all?
      sanitized == '*'
    end

    def short?
      id.length < 3
    end
  end
end

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
workarea-core-3.4.13 app/models/workarea/query_string.rb
workarea-core-3.4.12 app/models/workarea/query_string.rb