Fix bug with MongoidAdditions throwing a NameError when Mongoid is not defined by always checking if Mongoid is defined before referencing Mongoid-related constants

Also add spec for this bug
This commit is contained in:
Mani Tadayon 2010-12-26 02:17:50 -08:00
parent ebb8e1bf8b
commit e14e1edec2
2 changed files with 145 additions and 122 deletions

View File

@ -1,10 +1,9 @@
module CanCan
module Ability
# could use alias_method_chain, but it's not worth adding activesupport as a gem dependency
alias_method :query_without_mongoid_support, :query
def query(action, subject)
if Object.const_defined?(:Mongoid) && subject <= CanCan::MongoidAdditions
if defined?(::Mongoid) && subject <= CanCan::MongoidAdditions
query_with_mongoid_support(action, subject)
else
query_without_mongoid_support(action, subject)
@ -47,7 +46,7 @@ module CanCan
# => true
class Rule
def matches_conditions_hash_with_mongoid_subject?(subject, conditions = @conditions)
if subject.class.include?(Mongoid::Document) && conditions.any?{|k,v| !k.kind_of?(Symbol)}
if defined?(::Mongoid) && subject.class.include?(::Mongoid::Document) && conditions.any?{|k,v| !k.kind_of?(Symbol)}
if conditions.empty?
true
else
@ -98,7 +97,7 @@ end
# Info on monkeypatching Mongoid :
# http://log.mazniak.org/post/719062325/monkey-patching-activesupport-concern-and-you#footer
if defined? Mongoid
if defined?(::Mongoid)
module Mongoid
module Components
old_block = @_included_block

View File

@ -1,5 +1,5 @@
require 'mongoid' # require mongoid first so MongoidAdditions are loaded
require "spec_helper"
require 'mongoid'
class MongoidCategory
include Mongoid::Document
@ -38,6 +38,29 @@ Mongoid.configure do |config|
end
describe CanCan::MongoidAdditions do
context "Mongoid not defined" do
before(:all) do
@mongoid_class = Object.send(:remove_const, :Mongoid)
end
after(:all) do
Object.const_set(:Mongoid, @mongoid_class)
end
it "should not raise an error for ActiveRecord models" do
@model_class = Class.new(Project)
stub(@model_class).scoped { :scoped_stub }
@model_class.send(:include, CanCan::ActiveRecordAdditions)
@ability = Object.new
@ability.extend(CanCan::Ability)
@ability.can :read, @model_class
lambda {
@ability.can? :read, @model_class.new
}.should_not raise_error
end
end
context "Mongoid defined" do
before(:each) do
@model_class = MongoidProject
@ability = Object.new
@ -164,3 +187,4 @@ describe CanCan::MongoidAdditions do
}.should raise_error(CanCan::Error)
end
end
end