Created
December 8, 2009 11:34
-
-
Save remvee/251576 to your computer and use it in GitHub Desktop.
combine scopes from a hash
This file contains 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
# 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