class ElasticsearchQueryParser::Sentence

Transform user query to `Left to Right` expression for parser usage

Constants

WORD_SPLITTER_REGEX

Split by whitespace, but not split words in quotes

Attributes

sentence[R]

Public Class Methods

new(sentence) click to toggle source

Initialize with user input

# File lib/elasticsearch_query_parser/sentence.rb, line 11
def initialize(sentence)
  @sentence = sentence
end

Public Instance Methods

to_s() click to toggle source

Return valid for parser usage user input Example:

>> ElasticsearchQueryParser.new("(London AND Madrid) OR Paris").to_s
=> "Paris OR ( Madrid AND London )"
# File lib/elasticsearch_query_parser/sentence.rb, line 19
def to_s
  left_to_right? ? sentence : revert_left_to_right
end

Private Instance Methods

left_to_right?() click to toggle source

Left to Right expresstion starts with simple term instead of expression

# File lib/elasticsearch_query_parser/sentence.rb, line 38
def left_to_right?
  return true unless sentence

  sentence[0] != "("
end
prepared_sentence() click to toggle source

Add whitespace before/after parentheses

# File lib/elasticsearch_query_parser/sentence.rb, line 45
def prepared_sentence
  if sentence
    sentence.split("").reduce("") do |left_to_right_string, char|
      left_to_right_string + (["(", ")"].include?(char) ? " #{char} " : char)
    end
  else
    ""
  end
end
revert_left_to_right() click to toggle source
# File lib/elasticsearch_query_parser/sentence.rb, line 25
def revert_left_to_right
  prepared_sentence.scan(WORD_SPLITTER_REGEX).reverse.map do |word|
    if word == "("
      ")"
    elsif word == ")"
      "("
    else
      word
    end
  end.join(" ")
end