Class: Hanami::Utils::Class

Inherits:
Object
  • Object
show all
Defined in:
lib/hanami/utils/class.rb

Overview

Class utilities

Since:

  • 0.1.0

Class Method Summary collapse

Class Method Details

.load(name, namespace = Object) ⇒ Class, ...

Loads a class for the given name, only if it’s defined.

Examples:

require 'hanami/utils/class'

module App
  module Service
    class Endpoint
    end
  end

  class ServiceEndpoint
  end
end

# basic usage
Hanami::Utils::Class.load('App::Service') # => App::Service
Hanami::Utils::Class.load(App::Service)   # => App::Service

# with explicit namespace
Hanami::Utils::Class.load('Service', App) # => App::Service

Parameters:

  • name (String, Class)

    the specific class name

  • namespace (Class, Module) (defaults to: Object)

    the Ruby namespace where we want to perform the lookup.

Returns:

  • (Class, Module, NilClass)

    the Ruby constant, or nil if not found.

Since:

  • 0.8.0



71
72
73
# File 'lib/hanami/utils/class.rb', line 71

def self.load(name, namespace = Object)
  load!(name, namespace) if namespace.const_defined?(name.to_s, false)
end

.load!(name, namespace = Object) ⇒ Class, Module

Loads a class for the given name.

Examples:

require 'hanami/utils/class'

module App
  module Service
    class Endpoint
    end
  end

  class ServiceEndpoint
  end
end

# basic usage
Hanami::Utils::Class.load!('App::Service') # => App::Service
Hanami::Utils::Class.load!(App::Service)   # => App::Service

# with explicit namespace
Hanami::Utils::Class.load!('Service', App) # => App::Service

# with missing constant
Hanami::Utils::Class.load!('Unknown') # => raises NameError

Parameters:

  • name (String, Class)

    the specific class name

  • namespace (Class, Module) (defaults to: Object)

    the Ruby namespace where we want to perform the lookup.

Returns:

  • (Class, Module)

    the found Ruby constant.

Raises:

  • (NameError)

    if no constant can be found.

Since:

  • 0.1.0



40
41
42
# File 'lib/hanami/utils/class.rb', line 40

def self.load!(name, namespace = Object)
  namespace.const_get(name.to_s, false)
end