lib/minidusen/parser.rb in minidusen-0.8.0 vs lib/minidusen/parser.rb in minidusen-0.8.1
- old
+ new
@@ -1,35 +1,64 @@
module Minidusen
class Parser
+ class CannotParse < StandardError; end
+
TEXT_QUERY = /(?:(\-)?"([^"]+)"|(\-)?([\S]+))/
FIELD_QUERY = /(\-)?(\w+)\:#{TEXT_QUERY}/
- def self.parse(query_string)
- query_string = query_string.dup # we are going to delete substrings in-place
- query = Query.new
- extract_field_query_tokens(query_string, query)
- extract_text_query_tokens(query_string, query)
- query
- end
+ class << self
- def self.extract_text_query_tokens(query_string, query)
- while query_string.sub!(TEXT_QUERY, '')
- value = "#{$2}#{$4}"
- exclude = "#{$1}#{$3}" == "-"
- options = { :field => 'text', :value => value, :exclude => exclude }
- query << Token.new(options)
+ def parse(object)
+ case object
+ when Query
+ object
+ when String
+ parse_string(object)
+ when Array
+ parse_array(object)
+ else
+ raise CannotParse, "Cannot parse #{object.inspect}"
+ end
end
- end
- def self.extract_field_query_tokens(query_string, query)
- while query_string.sub!(FIELD_QUERY, '')
- field = $2
- value = "#{$4}#{$6}"
- exclude = "#{$1}" == "-"
- options = { :field => field, :value => value, :exclude => exclude }
- query << Token.new(options)
+ private
+
+ def parse_string(string)
+ string = string.dup # we are going to delete substrings in-place
+ query = Query.new
+ extract_field_query_tokens(string, query)
+ extract_text_query_tokens(string, query)
+ query
end
+
+ def parse_array(array)
+ tokens = array.map { |string|
+ string.is_a?(String) or raise CannotParse, "Cannot parse an array of #{string.class}"
+ Token.new(:field => 'text', :value => string)
+ }
+ Query.new(tokens)
+ end
+
+ def extract_text_query_tokens(query_string, query)
+ while query_string.sub!(TEXT_QUERY, '')
+ value = "#{$2}#{$4}"
+ exclude = "#{$1}#{$3}" == "-"
+ options = { :field => 'text', :value => value, :exclude => exclude }
+ query << Token.new(options)
+ end
+ end
+
+ def extract_field_query_tokens(query_string, query)
+ while query_string.sub!(FIELD_QUERY, '')
+ field = $2
+ value = "#{$4}#{$6}"
+ exclude = "#{$1}" == "-"
+ options = { :field => field, :value => value, :exclude => exclude }
+ query << Token.new(options)
+ end
+ end
+
end
end
end