Commit 157a4b09 authored by Kamil Trzciński's avatar Kamil Trzciński

Merge branch 'refactor-compute_class_for_class' into 'master'

Refactor policy class lookup

See merge request gitlab-org/gitlab!29667
parents 711ed1ba b287e354
......@@ -72,18 +72,17 @@ module DeclarativePolicy
end
def compute_class_for_class(subject_class)
if subject_class.respond_to?(:declarative_policy_class)
return subject_class.declarative_policy_class.constantize
end
subject_class.ancestors.each do |klass|
next unless klass.name
name = klass.name
next unless name
begin
klass_name =
if subject_class.respond_to?(:declarative_policy_class)
subject_class.declarative_policy_class
else
"#{klass.name}Policy"
end
policy_class = klass_name.constantize
policy_class = "#{name}Policy".constantize
# NOTE: the < operator here tests whether policy_class
# inherits from Base. We can't use #is_a? because that
......
# frozen_string_literal: true
require 'spec_helper'
describe DeclarativePolicy do
describe '.class_for' do
it 'uses declarative_policy_class if present' do
instance = Gitlab::ErrorTracking::ErrorEvent.new
expect(described_class.class_for(instance)).to eq(ErrorTracking::BasePolicy)
end
it 'infers policy class from name' do
instance = PersonalSnippet.new
expect(described_class.class_for(instance)).to eq(PersonalSnippetPolicy)
end
it 'raises error if not found' do
instance = Object.new
expect { described_class.class_for(instance) }.to raise_error('no policy for Object')
end
context 'when found policy class does not inherit base' do
class Foo; end
class FooPolicy; end
it 'raises error if inferred class does not inherit Base' do
instance = Foo.new
expect { described_class.class_for(instance) }.to raise_error('no policy for Foo')
end
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment