i'm wondering best way parse text query in rails is, allow user include logical operators?
i'd user able enter either of these, or equivalent:
# searching partial text in emails, example # query "jon , gmail" #=> ["jonsmith@gmail.com"] # query b "jon or gmail" #=> ["jonsmith@gmail.com", "sarahcalaway@gmail.com"] # query c "jon , gmail , smith" #=> ["jonsmith@gmail.com"] ideally, more complex parentheses indicate order of operations, that's not requirement.
is there gem or pattern supports this?
this possible inefficient way this:
user_input = "jon myers , gmail , smith or goldberg or moore" terms = user_input.split(/(.+?)((?: , | or ))/i).reject(&:empty?) # => ["jon myers", " , ", "gmail", " , ", "smith", " or ", "goldberg", " or ", "moore"] pairs = terms.each_slice(2).map { |text, op| ["column ? #{op} ", "%#{text}%"] } # => [["column ? , ", "%jon myers%"], ["column ? , ", "%gmail%"], ["column ? or ", "%smith%"], ["column ? or ", "%goldberg%"], ["column ? ", "%moore%"]] query = pairs.reduce([""]) { |acc, terms| acc[0] += terms[0]; acc << terms[1] } # => ["column ? , column ? , column ? or column ? or column ? ", "%jon myers%", "%gmail%", "%smith%", "%goldberg%", "%moore%"] model.where(query[0], *query[1..-1]).to_sql # => select "courses".* "courses" (column '%jon myers%' , column '%gmail%' , column '%smith%' or column '%goldberg%' or column '%moore%' ) however, said, searches 1 extremely inefficient. i'd recommend use full-text search engine, elasticsearch.
Comments
Post a Comment