switching data mapper to new adapter

This commit is contained in:
Ryan Bates 2010-12-30 14:53:56 -08:00
parent e8d298c223
commit f5dce44697
2 changed files with 26 additions and 33 deletions

View File

@ -1,32 +1,26 @@
module CanCan
module Ability
# could use alias_method_chain, but it's not worth adding activesupport as a gem dependency
alias_method :query_without_data_mapper_support, :query
def query(action, subject)
if Object.const_defined?('DataMapper') && subject <= DataMapper::Resource
query_with_data_mapper_support(action, subject)
else
query_without_data_mapper_support(action, subject)
end
module ModelAdapters
class DataMapperAdapter < AbstractAdapter
def self.for_class?(model_class)
model_class <= DataMapper::Resource
end
def query_with_data_mapper_support(action, subject)
DataMapperQuery.new(subject, relevant_rules_for_query(action, subject))
def database_records
scope = @model_class.all(:conditions => ['true=false'])
conditions.each do |condition|
scope += @model_class.all(:conditions => condition)
end
end
class DataMapperQuery
def initialize(sanitizer, rules)
@sanitizer = sanitizer
@rules = rules
scope
end
def conditions
@rules.map {|r| r.instance_variable_get(:@conditions) }
@rules.map(&:conditions)
end
end
end
end
# This module is automatically included into all Active Record models.
module CanCan
module DataMapperAdditions
module ClassMethods
# Returns a scope which fetches only the records that the passed ability
@ -47,14 +41,7 @@ module CanCan
# 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)
query = ability.query(action, self)
scope = all(:conditions => ['true=false'])
query.conditions.each do |condition|
scope += all(:conditions => condition)
end
return scope
ability.model_adapter(self, action).database_records
end
end
end

View File

@ -1,7 +1,7 @@
if ENV["MODEL_ADAPTER"] == "data_mapper"
require "spec_helper"
describe CanCan::DataMapperAdditions do
describe CanCan::ModelAdapters::DataMapperAdapter do
before(:each) do
@model_class = Class.new
@model_class.class_eval do
@ -13,6 +13,12 @@ if ENV["MODEL_ADAPTER"] == "data_mapper"
@ability.extend(CanCan::Ability)
end
it "should be for only data mapper classes" do
CanCan::ModelAdapters::DataMapperAdapter.should_not be_for_class(Object)
CanCan::ModelAdapters::DataMapperAdapter.should be_for_class(@model_class)
CanCan::ModelAdapters::AbstractAdapter.adapter_class(@model_class).should == CanCan::ModelAdapters::DataMapperAdapter
end
it "should return no records when no ability is defined so no records are found" do
@model_class.accessible_by(@ability, :read).should == 'no-match:'
end