Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid multiple queries on session dump #566

Merged
merged 1 commit into from
Feb 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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