module Enscoped::ClassMethods

Public Instance Methods

enscoped(*scopes) click to toggle source

Creates and executes a named scope for the given scopes. Ideally, this should do what scoped does. I’d like scoped to be called subsequently without executing first.

@return [] erm… what it returns and what it should return are

different
# File lib/enscoped.rb, line 61
def enscoped(*scopes)
  self.scoped(self.scope_for_scopes(*scopes))
end
scope_for_scopes(*scopes) click to toggle source

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]
}
# File lib/enscoped.rb, line 44
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