Skip to content

Commit

Permalink
avoid multiple queries on error pages (#566)
Browse files Browse the repository at this point in the history
  • Loading branch information
coorasse authored Feb 21, 2019
1 parent 0da5987 commit a68b21f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/cancan/rule.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions spec/cancan/rule_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit a68b21f

Please sign in to comment.