From d386a93e92c39d6f3eb24d7a086a318153c6c1e0 Mon Sep 17 00:00:00 2001 From: Ilya Grigorik Date: Mon, 28 Dec 2009 20:17:58 -0500 Subject: [PATCH] refactor grammar & no need to reload the grammar everytime --- README.rdoc | 4 ++-- lib/textquery/textquery.rb | 13 ++++++++++++- lib/textquery/textquery_grammar.treetop | 20 ++------------------ 3 files changed, 16 insertions(+), 21 deletions(-) diff --git a/README.rdoc b/README.rdoc index 877d0cd..88cd485 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,8 +1,8 @@ = TextQuery Does it match? When regular expressions are not enough, textquery is the answer. For -example, regular expressions cannot evaluate recursive rules, and often result in -overly verbosed and complicated expressions. +example, regular expressions cannot evaluate recursive rules and often result in +overly verbose and complicated expressions. Textquery is a simple PEG grammar with support for: - AND (spaces are implicit AND's) diff --git a/lib/textquery/textquery.rb b/lib/textquery/textquery.rb index 2c42d2a..878e2db 100644 --- a/lib/textquery/textquery.rb +++ b/lib/textquery/textquery.rb @@ -1,8 +1,19 @@ require 'treetop' +class WordMatch < Treetop::Runtime::SyntaxNode + def eval(text) + not text.match(/^#{query}\s|\s#{query}\s|\s#{query}$|^#{query}$/).nil? + end + + def query + Regexp.escape(text_value) + end +end + +Treetop.load File.dirname(__FILE__) + "/textquery_grammar" + class TextQuery def initialize(query = '') - Treetop.load File.dirname(__FILE__) + "/textquery_grammar" @parser = TextQueryGrammarParser.new @query = nil diff --git a/lib/textquery/textquery_grammar.treetop b/lib/textquery/textquery_grammar.treetop index 3d18c1f..c404012 100644 --- a/lib/textquery/textquery_grammar.treetop +++ b/lib/textquery/textquery_grammar.treetop @@ -45,27 +45,11 @@ grammar TextQueryGrammar end rule word - [^\s\(\)]+ { - def eval(text) - not text.match(/^#{query}\s|\s#{query}\s|\s#{query}$|^#{query}$/).nil? - end - - def query - Regexp.escape(text_value) - end - } + [^\s\(\)]+ end rule words - [^\']+ { - def eval(text) - not text.match(/^#{query}\s|\s#{query}\s|\s#{query}$|^#{query}$/).nil? - end - - def query - Regexp.escape(text_value) - end - } + [^\']+ end rule value