From c1839d5dccf0c1fe07585f14444f19aa5b6e0da9 Mon Sep 17 00:00:00 2001 From: alexyndr belik Date: Thu, 12 Nov 2020 14:15:06 +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..b8527dba --- /dev/null +++ b/lib/macro/pundit.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +module Policy + def self.Pundit(policy_class, user, model, 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: nil, model: nil, 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