Skip to content

Instantly share code, notes, and snippets.

@remvee
Created December 8, 2009 11:34
Show Gist options
  • Save remvee/251576 to your computer and use it in GitHub Desktop.
Save remvee/251576 to your computer and use it in GitHub Desktop.
combine scopes from a hash
# Allow query usings scopes and arguments from a hash. Useful for
# making index actions.
#
# Example:
#
# User.with_scopes(:search => "Fred")
#
# Where +search+ is a named scope on +User+ which excepts a parameter.
module WithScopes
# Determine if named scope exists.
def has_scope?(name)
scopes.keys.map(&:to_s).include?(name.to_s)
end
# Run through given scopes.
def with_scopes(params)
params.select do |k,_|
has_scope?(k)
end.inject(self) do |scope,(k,v)|
scopes[k.to_sym][scope, *v]
end
end
end
class ActiveRecord::Base; extend WithScopes; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment