Created
March 28, 2011 19:25
-
-
Save jmorton/891096 to your computer and use it in GitHub Desktop.
Helper method for building a named scope from a list of scope names
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
module Enscoped | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
# Create one named scope from many named scopes. | |
# | |
# @param [Array<String or Symbol>] scope names | |
# @return [Hash] hash compatible with ActiveRecord::Base#scoped | |
# | |
# Example: | |
# | |
# Book.scope_for_scopes(:short, :informative, :free) | |
# | |
# %w(short informative free).inject(Hash.new) { |memo, name| | |
# self.scoped(memo).send(name).current_scoped_methods[:find] | |
# } | |
# | |
def scope_for_scopes(*scopes) | |
# intersect valid scope names so dangerous methods | |
# like destroy_all aren't invoked! | |
safe_scopes = self.scopes.keys & scopes.map(&:to_sym) | |
# build (and return) a hash of the constructed scope | |
safe_scopes.inject({}) { |memo, scope| | |
self.scoped(memo).send(scope).current_scoped_methods[:find] | |
} | |
end | |
def enscoped(*scopes) | |
self.scoped(self.scope_for_scopes(*scopes)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment