0

I'm sure this has been done before, I just can't find it.

I need to turn something like, "((A OR B) AND C) OR D" into a database query for an attribute. Specifically I'm using Ruby Sequel. Can anyone point me at an example or utility or something that will keep me from reinventing the wheel?

2
  • Have a look at treetop: treetop.rubyforge.org Commented Aug 29, 2012 at 7:56
  • Thanks fellas. I was basically looking for code / pseudocode that already did what I was talking about. We're only talking about three operators here, right? I'm sure its out there somewhere as this doesn't seem to be a terribly unusual thing to do. Anyway, we are in a hurry so we just bailed on parentheses for now (current customers can do without). Handling just AND and OR is no problem in a single pass. We'll revisit this later and implement parentheses. Commented Aug 30, 2012 at 13:20

1 Answer 1

2

You can define a grammar using ANTLR and automatically generate a Ruby parser for those type of strings. ANTLR is a parser generator and it allows you to define a grammar for a language (such as a the boolean language that you described).

After parsing, you can specify what actions need to be taken to build the desired data structure (in your case a tree data structure that captures the structure of the query).

This is not particularly a Ruby problem as ANTLR can also generate parsers for other languages. In your case it would produce a Ruby parser that you can integrate into your application to parse the strings and to produce the data structure that you need.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.