Add support for Mongoid::Criteria Symbol extensions (:age.gt => 10) along with specs.

This commit is contained in:
Mani Tadayon
2010-10-13 15:22:53 -07:00
parent be74df0548
commit ab82dcbc8f
3 changed files with 89 additions and 3 deletions

View File

@@ -26,6 +26,42 @@ module CanCan
end
end
# customize to handle Mongoid queries in ability definitions conditions
class CanDefinition
def matches_conditions_hash?(subject, conditions = @conditions)
if subject.class.include?(Mongoid::Document) # Mongoid Criteria are simpler to check than normal conditions hashes
if conditions.empty? # When no conditions are given, true should be returned.
# The default CanCan behavior relies on the fact that conditions.all? will return true when conditions is empty
# The way ruby handles all? for empty hashes can be unexpected:
# {}.all?{|a| a == 5}
# => true
# {}.all?{|a| a != 5}
# => true
true
else
subject.class.where(conditions).include?(subject) # just use Mongoid's where function
end
else
conditions.all? do |name, value|
attribute = subject.send(name)
if value.kind_of?(Hash)
if attribute.kind_of? Array
attribute.any? { |element| matches_conditions_hash? element, value }
else
matches_conditions_hash? attribute, value
end
elsif value.kind_of?(Array) || value.kind_of?(Range)
value.include? attribute
else
attribute == value
end
end
end
end
end
module MongoidAdditions
module ClassMethods
# Returns a scope which fetches only the records that the passed ability