Minor refactoring

This commit is contained in:
Andrew Haines 2012-11-15 12:57:08 +00:00
parent fd7dc05436
commit 761d60528b
1 changed files with 20 additions and 16 deletions

View File

@ -1,44 +1,48 @@
module Draper module Draper
class Security class Security
def initialize def initialize
@allowed = [] @methods = []
@denied = []
end end
def denies(*methods) def denies(*methods)
raise ArgumentError, "Specify at least one method to blacklist when using denies" if methods.empty? apply_strategy :denies
self.strategy = :denies add_methods methods
@denied += methods.map(&:to_sym)
end end
def denies_all def denies_all
self.strategy = :denies_all apply_strategy :denies_all
end end
def allows(*methods) def allows(*methods)
raise ArgumentError, "Specify at least one method to whitelist when using allows" if methods.empty? apply_strategy :allows
self.strategy = :allows add_methods methods
@allowed += methods.map(&:to_sym)
end end
def allow?(method) def allow?(method)
case strategy case strategy
when :allows when :allows
allowed.include?(method) methods.include?(method)
when :denies, nil when :denies
!denied.include?(method) !methods.include?(method)
when :denies_all when :denies_all
false false
when nil
true
end end
end end
private private
attr_reader :allowed, :denied, :strategy attr_reader :methods, :strategy
def strategy=(strategy) def apply_strategy(new_strategy)
@strategy ||= strategy raise ArgumentError, "Use only one of 'allows', 'denies', or 'denies_all'." if strategy && strategy != new_strategy
raise ArgumentError, "Use only one of 'allows', 'denies', or 'denies_all'." unless @strategy == 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 end
end end