Sha256: 73ff1ce89abb46634eee0152235e1577e7de66f52fc171c6ca7e376ef885f1f2
Contents?: true
Size: 1.6 KB
Versions: 16
Compression:
Stored size: 1.6 KB
Contents
# Used the following blog post as a starting point, then completely rewrote the parser: # http://proccli.com/2011/12/advanced-search-query-parsing-ruby/ # https://gist.github.com/1477730#file_search_terms.rb module MongoRequestLogger class SearchTerms attr_reader :query, :parts, :search, :path, :search_regex # query:: this is what you want tokenized # split:: if you'd like to split values on "," then pass true def initialize(query) @query = query @parts = {} @search = nil @search_regex = nil parse_query end def [](key) @parts[key] end private SCANNER = /(?:(\w+):(\S+)) # key:value |(?:"(.+)") # string in quotes |(^\S+) # a path |(?:\/(.+?)\/(?:\s|$)) # regular expression |(\S+)/x # a word def parse_query search_parts = [] search_regex = nil # We break up the query into a sequence of the following possible components: # key:value # "a string wrapped in quotes" # /a/path (at the beginning of the string only) # /a regular expression/ # word groups = @query.scan(SCANNER) groups.map do |key, value, search, path, regex, word| if key @parts[key.downcase] = value elsif search search_parts << search elsif regex @search_regex = regex elsif path @path = path elsif word search_parts << word end end unless @search_regex @search = search_parts.join(' ') end end end end
Version data entries
16 entries across 16 versions & 1 rubygems