Skip to content

Instantly share code, notes, and snippets.

@stevecrozz
Last active December 2, 2015 06:54
Show Gist options
  • Select an option

  • Save stevecrozz/e4f8213e0b8d5e556edb to your computer and use it in GitHub Desktop.

Select an option

Save stevecrozz/e4f8213e0b8d5e556edb to your computer and use it in GitHub Desktop.
Query Syntax Parser
require 'pry'
class MagicBullshit
def self.inherited(subclass)
subclass.prepare
end
def self.prepare
@words = {}
end
def self.parse(s)
raw = s.scan(/([+-])?(?:(\S+)\:\s?)?(?:(?:"(.+?)")|(\S+))/).map do |m|
Hash[[:plusminus, :prefix, :phrase, :word].zip(m).select(&:all?)]
end
self.new(raw)
end
def self.magic_word(word, type)
@words[word] = type
end
def self.magic_words
@words
end
def initialize(raw)
@raw = raw
decorate_magic_words
end
def decorate_magic_words
@baked = @raw.map do |r|
b = r.dup
if type = self.class.magic_words[r[:prefix]]
if type == :string
b[:magic] = b[:word] || b[:phrase]
elsif type == :date
matches = b[:word].match(/^(<=|<|>|>=)?(.+)$/)
b[:magic] = {}
b[:magic][:sign] = matches[1] if matches[1]
b[:magic][:date] = Date.parse(matches[2])
end
else
b[:word] || b[:phrase]
end
b
end
end
end
class MyBullshit < MagicBullshit
magic_word 'language', :string
end
class MyOtherBullshit < MagicBullshit
magic_word 'created', :date
end
puts MyBullshit.parse('language:c# created:<2011-01-01 state:open').inspect
puts MyOtherBullshit.parse('language:c# created:<2011-01-01 state:open').inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment