Sha256: f474ad37c9fd8224e2e25667bc82665689046052fa97db979d0df8e58f098a6c

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

require 'adeia/controller_resource'
require 'adeia/exceptions'

module Adeia

  module ControllerMethods

    module ClassMethods

      def load_and_authorize(**args)
        ControllerResource.add_before_filter(self, :load_resource_or_records_and_authorize, **args)
      end

      def require_login(**args)
        ControllerResource.add_before_filter(self, :require_login, **args)
      end

    end

    def self.included(base)
      base.extend ClassMethods
      base.helper_method :can?
    end

    def load_and_authorize!(**args)
      controller_resource = ControllerResource.new(self, **args)
      resource = controller_resource.load_resource
      controller_resource.authorize!
      return resource
    end

    def authorize_and_load_records!(**args)
      controller_resource = ControllerResource.new(self, **args)
      controller_resource.check_permissions!
      return controller_resource.load_records
    end

    def authorize!(**args)
      ControllerResource.new(self, **args).authorize!
    end

    def require_login!
      raise LoginRequired unless signed_in?
    end

    def can?(action, controller=nil, resource=nil)
      args = { action: action, controller: controller, resource: resource }
      var_name = "@#{action}#{controller.parameterize}#{resource.try(:model_name).try(:human)}#{resource.try(:id)}"
      instance_variable_get(var_name) || instance_variable_set(var_name, ControllerResource.new(self, **args).can?)
    end

    # Redirect the user to the stored url or the default one provided
    # 
    # * *Args*    :
    #   - default path to redirect to
    # * *Returns* :
    #
    def redirect_back_or(default, message = nil)
      redirect_to(cookies[:return_to] || default, message)
      cookies.delete(:return_to)
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
adeia-0.8.5 lib/adeia/controller_methods.rb