From f28f00e358b47a016e6198589593a707c2521bb3 Mon Sep 17 00:00:00 2001 From: alexyndr belik Date: Thu, 12 Nov 2020 14:19:32 +0200 Subject: [PATCH] ISSUE-264 | Add custom Policy macros --- lib/macro/pundit.rb | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 lib/macro/pundit.rb diff --git a/lib/macro/pundit.rb b/lib/macro/pundit.rb new file mode 100644 index 00000000..4780f434 --- /dev/null +++ b/lib/macro/pundit.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +module Policy + def self.Pundit(policy_class, user: nil, model: nil, action, name: :default) + Policy.step(Pundit.build(policy_class, user, model, action), name: name) + end + + module Pundit + def self.build(*args, &block) + Condition.new(*args, &block) + end + + class Condition + def initialize(policy_class, user, model, action) + @policy_class, @user, @model, @action = policy_class, user, model, action + end + + def call((options), *) + policy = build_policy + result!(policy.send(@action), policy) + end + + private + def build_policy + @policy_class.new(@user, @model) if @user && @model + @policy_class.new(options[:current_user], options[:model]) unless @user && @model + end + + def result!(success, policy) + data = { policy: policy } + data[:message] = "Breach" if !success + + Trailblazer::Operation::Result.new(success, data) + end + end + end +end