Module: Enscoped::ClassMethods

Defined in:
lib/enscoped.rb

Instance Method Summary collapse

Instance Method Details

#enscoped(*scopes) ⇒ Object

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.

Returns:

  • erm… what it returns and what it should return are

    different



61
62
63
# File 'lib/enscoped.rb', line 61

def enscoped(*scopes)
  self.scoped(self.scope_for_scopes(*scopes))
end

#scope_for_scopes(*scopes) ⇒ Hash

Create one named scope from many named scopes.

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]
}

Parameters:

  • scope (Array<String or Symbol>)

    names

Returns:

  • (Hash)

    hash compatible with ActiveRecord::Base#scoped



44
45
46
47
48
49
50
51
52
53
# 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