Fork me on GitHub

KeywordSearch 1.3.1

2007-10-09

KeywordSearch is a small library I wrote earlier this year to add support for GMail-style keyword/value searches via a DSL. It’s a parser pet project that I tweak from time-to-time.

Here’s an example, albeit a little hackish:

# Some variables to build up
clauses = []
arguments = []
# Search a string, defining the supported keywords and building up
# the variables in the associated closures
KeywordSearch.search('account has:attachment since:2006-12-03') do |with|
  with.default_keyword :title # values without keywords get assigned to this
  with.keyword :title do |values|
    # keyword blocks are yielded an array of values
    clauses << "title like ?"
    arguments << "%#{values.join(' ')}%"
  end
  with.keyword :has do |values|
    clauses << 'has_attachment = true' if values.include?('attachment')
  end
  with.keyword :since do |values|
    date = Date.parse(values.first) # only support one
    clauses << 'created_on >= ?'
    arguments << date.to_s
  end
end

# Do our search with clauses and arguments

conditions = [clauses.map{|c| "(#{c})"}.join(' AND ')), *arguments] # simplistic example
results = Message.find(:all, :conditions => conditions)

KeywordSearch is available from RubyForge and can be installed via:

sudo gem install keyword_search

Comments, as always, are welcome.

Changes in this release:

* Conversion to a Ragel parser as a performance tweak (not to mention less code). (I still love Dhaka, though).

* More advanced parsing with better character set support

* Test suite now uses “test/spec”: and has been added to significantly

* Keywords/values are now case sensitive; downcase the input manually if you want the old behavior.

Discussion