Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
20 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,48 @@ | ||
module Draper | ||
class Security | ||
def initialize | ||
@allowed = [] | ||
@denied = [] | ||
@methods = [] | ||
end | ||
|
||
def denies(*methods) | ||
raise ArgumentError, "Specify at least one method to blacklist when using denies" if methods.empty? | ||
self.strategy = :denies | ||
@denied += methods.map(&:to_sym) | ||
apply_strategy :denies | ||
add_methods methods | ||
end | ||
|
||
def denies_all | ||
self.strategy = :denies_all | ||
apply_strategy :denies_all | ||
end | ||
|
||
def allows(*methods) | ||
raise ArgumentError, "Specify at least one method to whitelist when using allows" if methods.empty? | ||
self.strategy = :allows | ||
@allowed += methods.map(&:to_sym) | ||
apply_strategy :allows | ||
add_methods methods | ||
end | ||
|
||
def allow?(method) | ||
case strategy | ||
when :allows | ||
allowed.include?(method) | ||
when :denies, nil | ||
!denied.include?(method) | ||
methods.include?(method) | ||
when :denies | ||
!methods.include?(method) | ||
when :denies_all | ||
false | ||
when nil | ||
true | ||
end | ||
end | ||
|
||
private | ||
|
||
attr_reader :allowed, :denied, :strategy | ||
attr_reader :methods, :strategy | ||
|
||
def strategy=(strategy) | ||
@strategy ||= strategy | ||
raise ArgumentError, "Use only one of 'allows', 'denies', or 'denies_all'." unless @strategy == strategy | ||
def apply_strategy(new_strategy) | ||
raise ArgumentError, "Use only one of 'allows', 'denies', or 'denies_all'." if strategy && strategy != new_strategy | ||
@strategy = new_strategy | ||
end | ||
|
||
def add_methods(new_methods) | ||
raise ArgumentError, "Specify at least one method when using #{strategy}" if new_methods.empty? | ||
@methods += new_methods.map(&:to_sym) | ||
end | ||
end | ||
end |