Created
August 23, 2012 05:24
-
-
Save tastycode/3432933 to your computer and use it in GitHub Desktop.
Holy Hash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'set' | |
def search(&block) | |
query_config = Object.new | |
class << query_config | |
def method_missing method_name, *args, &block | |
sym_variable = "@#{method_name}".to_sym | |
return dynamic_set("@#{$1}", args.first) if method_name.to_s =~ /(.*)=$/ | |
return dynamic_get(sym_variable) if user_variables.include? sym_variable | |
super | |
end | |
def dynamic_set var_name, val | |
instance_variable_set var_name, val | |
user_variables << var_name.to_sym | |
end | |
def dynamic_get var_name | |
instance_variable_get var_name | |
end | |
def user_variables | |
@user_variables ||= Set.new | |
end | |
def cursor &block | |
@cursor = block | |
end | |
def next &block | |
@next = block | |
end | |
def catch &block | |
@catch = block | |
end | |
end | |
def configurer block | |
Proc.new do |query_config| | |
block.call query_config | |
query_config | |
end | |
end | |
configured = configurer(block).call query_config | |
configured.extend(Module.new do | |
attr_accessor :haystack | |
def invoke haystack | |
@haystack = haystack | |
while @target = @cursor.() | |
unless @catch.nil? | |
return @target if @catch.(@target) | |
end | |
@next.() | |
end | |
end | |
end) | |
configured | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sample = [ | |
{ | |
:name => "john", | |
:likes => ["fishing", "boating"] | |
}, | |
{ | |
:name => "tom", | |
:likes => ["biking", "hiking"] | |
}, | |
{ | |
:name => "chris", | |
:likes => ["searching", "boating"] | |
}, | |
{ | |
:name => "fox", | |
:likes => ["canoeing", "boating"] | |
} | |
] | |
require './holy_hash_search' | |
query = search do |sniffer| | |
sniffer.i = 0 | |
sniffer.cursor do | |
sniffer.haystack[sniffer.i] | |
end | |
sniffer.next do | |
sniffer.i += 1 | |
end | |
sniffer.catch do |cursor| | |
cursor[:likes].include? "hiking" | |
end | |
end | |
p query.invoke(sample) # => [:name => "tom", :likes => ["biking", "hiking"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment