Created
May 14, 2010 20:27
-
-
Save blackgold9/401624 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 CanCan | |
# This module is automatically included into all Mongoid | |
module MongoidAdditions | |
module ClassMethods | |
# Returns a scope which fetches only the records that the passed ability | |
# can perform a given action on. The action defaults to :read. This | |
# is usually called from a controller and passed the +current_ability+. | |
# | |
# @articles = Article.accessible_by(current_ability) | |
# | |
# Here only the articles which the user is able to read will be returned. | |
# If the user does not have permission to read any articles then an empty | |
# result is returned. Since this is a scope it can be combined with any | |
# other scopes or pagination. | |
# | |
# An alternative action can optionally be passed as a second argument. | |
# | |
# @articles = Article.accessible_by(current_ability, :update) | |
# | |
# Here only the articles which the user can update are returned. This | |
# internally uses Ability#conditions method, see that for more information. | |
def accessible_by(ability, action = :read) | |
conditions = ability.conditions(action, self) || {:id => nil} | |
if respond_to? :where | |
where(conditions) | |
else | |
scoped(:conditions => conditions) | |
end | |
end | |
end | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
end | |
end | |
if defined? Mongoid | |
Mongoid::Document.module_eval do | |
include CanCan::MongoidAdditions | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment