Skip to content

Commit

Permalink
ISSUE-264 | Add custom Policy macros
Browse files Browse the repository at this point in the history
  • Loading branch information
alexyndr committed Nov 12, 2020
1 parent bbc69a0 commit c1839d5
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lib/macro/pundit.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit c1839d5

Please sign in to comment.