require 'active_support/inflector'

module Guardsman
  # Find and instantiate a guard class.
  class Guard
    class << self
      # Instantiates a guard object for the given
      # scope. The object must be previously
      # loaded, otherwise an error is raised
      #
      # @param [Object] request A request object.
      # @param [String] scope Prefix name of a guard class.
      #
      # @return [Object] Instantiated guard object.
      def find!(request, scope)
        klass = guard_class(scope)
        klass.new(request, scope)
      end

      private

      # The guard class for the scope. The guard
      # class is constructed from the scope name
      # and "Guard" suffix
      #
      # @param [String] scope Prefix name of a guard class.
      #
      # @return [Class] Guard class constant.
      def guard_class(scope)
        return scope if scope.nil?
        "#{scope}Guard".constantize
      end
    end
  end
end
