summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorhttp://jneen.net/ <jneen@jneen.net>2016-08-30 11:09:21 -0700
committerhttp://jneen.net/ <jneen@jneen.net>2016-08-30 11:39:22 -0700
commit57def53c84091a56f3a2443d214fe80f2c026d00 (patch)
tree6acfe610ab3112c929e0781a2f9aaa16ea6ea878
parentb3b7fb1fe7b876487b1464aa5779bacec7276742 (diff)
downloadgitlab-ce-57def53c84091a56f3a2443d214fe80f2c026d00.tar.gz
factor out a RuleSet so that `delegate!` retains @cannot
-rw-r--r--app/models/ability.rb2
-rw-r--r--app/policies/base_policy.rb58
2 files changed, 51 insertions, 9 deletions
diff --git a/app/models/ability.rb b/app/models/ability.rb
index 8ccbb9bee9c..fa8f8bc3a5f 100644
--- a/app/models/ability.rb
+++ b/app/models/ability.rb
@@ -55,7 +55,7 @@ class Ability
user_key = user ? user.id : 'anonymous'
subject_key = subject ? "#{subject.class.name}/#{subject.id}" : 'global'
key = "/ability/#{user_key}/#{subject_key}"
- RequestStore[key] ||= Set.new(uncached_allowed(user, subject)).freeze
+ RequestStore[key] ||= uncached_allowed(user, subject).freeze
end
private
diff --git a/app/policies/base_policy.rb b/app/policies/base_policy.rb
index a6fd9786ae7..6a1a7d75ee6 100644
--- a/app/policies/base_policy.rb
+++ b/app/policies/base_policy.rb
@@ -1,4 +1,47 @@
class BasePolicy
+ class RuleSet
+ attr_reader :can_set, :cannot_set
+ def initialize(can_set, cannot_set)
+ @can_set = can_set
+ @cannot_set = cannot_set
+ end
+
+ def self.empty
+ new(Set.new, Set.new)
+ end
+
+ def can?(ability)
+ @can_set.include?(ability) && !@cannot_set.include?(ability)
+ end
+
+ def include?(ability)
+ can?(ability)
+ end
+
+ def to_set
+ @can_set - @cannot_set
+ end
+
+ def merge(other)
+ @can_set.merge(other.can_set)
+ @cannot_set.merge(other.cannot_set)
+ end
+
+ def can!(*abilities)
+ @can_set.merge(abilities)
+ end
+
+ def cannot!(*abilities)
+ @cannot_set.merge(abilities)
+ end
+
+ def freeze
+ @can_set.freeze
+ @cannot_set.freeze
+ super
+ end
+ end
+
def self.abilities(user, subject)
new(user, subject).abilities
end
@@ -30,7 +73,7 @@ class BasePolicy
end
def abilities
- return [] if @user && @user.blocked?
+ return RuleSet.empty if @user && @user.blocked?
return anonymous_abilities if @user.nil?
collect_rules { rules }
end
@@ -44,27 +87,26 @@ class BasePolicy
end
def delegate!(new_subject)
- @can.merge(Ability.allowed(@user, new_subject))
+ @rule_set.merge(Ability.allowed(@user, new_subject))
end
def can?(rule)
- @can.include?(rule) && !@cannot.include?(rule)
+ @rule_set.can?(rule)
end
def can!(*rules)
- @can.merge(rules)
+ @rule_set.can!(*rules)
end
def cannot!(*rules)
- @cannot.merge(rules)
+ @rule_set.cannot!(*rules)
end
private
def collect_rules(&b)
- @can = Set.new
- @cannot = Set.new
+ @rule_set = RuleSet.empty
yield
- @can - @cannot
+ @rule_set
end
end