Skip to content

Instantly share code, notes, and snippets.

@paulcc
Created December 6, 2010 11:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulcc/730167 to your computer and use it in GitHub Desktop.
Save paulcc/730167 to your computer and use it in GitHub Desktop.
Import this to get searchlogic-style scopes from metasearch and rails 3
# by Paul Callaghan, Nov 2010.
# this uses method-missing to trigger generation and execution of the corresponding relation
# eg Product.name_equals("yay")
# TODO: M_S doesn't check for unexpected values, eg match failures in
# matches_attribute_method (so we trap exceptions)
module MetaSearchHacks
def self.build_rel(base_or_scope, method, *args)
begin
MetaSearch::Builder.
new(base_or_scope).
method_missing(method.to_s + '=', *args)
rescue => e
return nil
end
end
end
# fix for relation/scope values
class ActiveRecord::Relation
include MetaSearchHacks
def method_missing_with_metasearch(method, *args)
if relation = MetaSearchHacks.build_rel(self.klass, method, *args)
return self.merge(relation)
elsif self.respond_to? :method_missing_without_metasearch
self.method_missing_without_metasearch(method, *args)
else
raise "Couldn't run instance's original method_missing()"
end
end
alias_method_chain :method_missing, :metasearch
end
# but for models, we want to create new scope-like things
class ActiveRecord::Base
# this alias must be done in the singleton class
class << self
# alias_method_chain :method_missing, :metasearch
end
end
class ActiveRecord::Base
include MetaSearchHacks
protected
def self.method_missing_with_metasearch(method, *args)
if relation = MetaSearchHacks.build_rel(self, method, *args)
return relation
else
# respond_to doesn't like private/protected methods?
self.send(:method_missing_without_metasearch, method, *args)
end
end
# this alias must be done in the singleton class
class << self
alias_method_chain :method_missing, :metasearch
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment