module AuthorizedTransaction

Constants

VERSION

Public Class Methods

configure(&block) click to toggle source
# File lib/authorized_transaction.rb, line 12
def self.configure(&block)
  block_given? ? instance_exec(self, &block) : self
end

Public Instance Methods

authorize!(action, resource) click to toggle source
# File lib/authorized_transaction.rb, line 58
def authorize!(action, resource)
  Array(resource).each do |r|
    next if authorized?(action, r)
    raise TransactionUnauthorized.new(action, r)
  end
end
authorized_transaction(action: implicit_action) { || ... } click to toggle source

Wraps a block in a transaction after which the authorization check runs, using the controller action as default

+action+ and the return value of the block as +resource+

@param action [Symbol] @yields a block to run actions and return a resource

@throws TransactionUnauthorized

when the +resource+ could not be +action+

@example create a book first and check afterwards if it was allowed

class BookController < ApiController
  def create
    @book = authorized_transaction { CreateAndReturnBook.call(params) }
    render json: @book, status: :created
  end
end
# File lib/authorized_transaction.rb, line 50
def authorized_transaction(action: implicit_action)
  create_transaction do
    resource = yield
    authorize! action, resource
    resource
  end
end

Private Instance Methods

authorized?(action, resource) click to toggle source
# File lib/authorized_transaction.rb, line 85
def authorized?(action, resource)
  if authorize_proc.respond_to?(:call)
    return instance_exec(action, resource, self, &authorize_proc)
  end

  can?(action, resource)
end
create_transaction(&block) click to toggle source
# File lib/authorized_transaction.rb, line 76
def create_transaction(&block)
  if transaction_proc.respond_to?(:call)
    transaction_proc.call(&block)
  else
    # Expect active record to be loaded by now
    ActiveRecord::Base.transaction(&block)
  end
end
implicit_action() click to toggle source
# File lib/authorized_transaction.rb, line 68
def implicit_action
  if implicit_action_proc.respond_to?(:call)
    return instance_exec(self, &implicit_action_proc)
  end

  params[implicit_action_key || :action]
end