-
-
Save AMHOL/b0f3e3c3e7b34c155acdddda3eee6f2a to your computer and use it in GitHub Desktop.
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
module Dry | |
module Policy | |
Unauthorized = Class.new(StandardError) | |
def self.included(klass) | |
klass.extend(Dry::Container::Mixin) | |
klass.extend(ClassMethods) | |
klass.setting(:unauthorized_exception, Dry::Policy::Unauthorized) | |
end | |
module ClassMethods | |
def check(subject, ability, verb, **object) | |
key = _resolve_key(ability, verb, object.keys.first) | |
self[key].call(subject, object.values.first) | |
end | |
def abilities(*abilities) | |
abilities.each { |ability| _add_ability(ability) } | |
end | |
def ability(ability, verb, object_identitifer = nil, &policy) | |
register( | |
_resolve_key(ability, verb, object_identitifer), | |
&policy | |
) | |
end | |
def _resolve_key(*parts) | |
parts.compact.join(config.namespace_separator) | |
end | |
private | |
def _add_ability(ability) | |
define_method(ability) do |verb, **object| | |
self.class.check(subject, ability, verb, **object) | |
end | |
alias_method "#{ability}?", ability | |
end | |
end | |
attr_reader :subject | |
private :subject | |
def initialize(subject) | |
@subject = subject | |
end | |
def check(ability, verb, **object) | |
self.class.check(subject, ability, verb, **object) | |
end | |
def ensure!(ability, verb, **object) | |
check(ability, verb, **object) || fail( | |
self.class.config.unauthorized_exception | |
) | |
end | |
end | |
end |
Author
AMHOL
commented
Apr 15, 2016
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment