From f4741093a91f3aada09b0329862bf87305034d13 Mon Sep 17 00:00:00 2001 From: Alessandro Rodi Date: Thu, 21 Feb 2019 18:56:10 +0100 Subject: [PATCH] avoid multiple queries on error pages --- lib/cancan/rule.rb | 7 +++++++ spec/cancan/rule_spec.rb | 31 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lib/cancan/rule.rb b/lib/cancan/rule.rb index 6ba747fe..fb8881ff 100644 --- a/lib/cancan/rule.rb +++ b/lib/cancan/rule.rb @@ -29,6 +29,13 @@ def initialize(base_behavior, action, subject, *extra_args, &block) @block = block end + def inspect + repr = "#<#{self.class.name}" + repr << "#{@base_behavior ? 'can' : 'cannot'} #{@actions.inspect}, #{@subjects.inspect}, #{@attributes.inspect}" + repr << @conditions.inspect.to_s if [Hash, String].include?(@conditions.class) + repr << '>' + end + def can_rule? base_behavior end diff --git a/spec/cancan/rule_spec.rb b/spec/cancan/rule_spec.rb index 7d0966df..0f467bc1 100644 --- a/spec/cancan/rule_spec.rb +++ b/spec/cancan/rule_spec.rb @@ -58,4 +58,35 @@ expect(rule2.attributes).to eq [] expect(rule2.conditions).to eq %i[foo bar] end + + describe '#inspect' do + def count_queries(&block) + count = 0 + counter_f = lambda { |_name, _started, _finished, _unique_id, payload| + count += 1 unless payload[:name].in? %w[CACHE SCHEMA] + } + ActiveSupport::Notifications.subscribed(counter_f, 'sql.active_record', &block) + count + end + + before do + ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') + ActiveRecord::Migration.verbose = false + ActiveRecord::Schema.define do + create_table(:watermelons) do |t| + t.boolean :visible + end + end + + class Watermelon < ActiveRecord::Base + scope :visible, -> { where(visible: true) } + end + end + + it 'does not evaluate the conditions when they are scopes' do + rule = CanCan::Rule.new(true, :read, Watermelon, Watermelon.visible, {}, {}) + count = count_queries { rule.inspect } + expect(count).to eq 0 + end + end end