Class: Lotus::Utils::Class

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

Overview

Class utilities

Since:

  • 0.1.0

Class Method Summary collapse

Class Method Details

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

Loads a class for the given name.

Examples:

require 'lotus/utils/class'

module App
  module Service
    class Endpoint
    end
  end

  class ServiceEndpoint
  end
end

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

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

# with missing constant
Lotus::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/lotus/utils/class.rb', line 40

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

.load_from_pattern!(pattern, namespace = Object) ⇒ Class, Module

Loads a class from the given pattern name and namespace

Examples:

require 'lotus/utils/class'

module App
  module Service
    class Endpoint
    end
  end

  class ServiceEndpoint
  end
end

# basic usage
Lotus::Utils::Class.load_from_pattern!('App::Service') # => App::Service

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

# with pattern
Lotus::Utils::Class.load_from_pattern!('App::Service(::Endpoint|Endpoint)') # => App::Service::Endpoint
Lotus::Utils::Class.load_from_pattern!('App::Service(Endpoint|::Endpoint)') # => App::ServiceEndpoint

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

Parameters:

  • pattern (String)

    the class name pattern

  • 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.

See Also:

Since:

  • 0.3.1



81
82
83
84
85
86
87
88
89
90
91
# File 'lib/lotus/utils/class.rb', line 81

def self.load_from_pattern!(pattern, namespace = Object)
  String.new(pattern).tokenize do |token|
    begin
      return namespace.const_get(token)
    rescue NameError
    end
  end

  full_name = [ (namespace == Object ? nil : namespace), pattern ].compact.join('::')
  raise NameError.new("uninitialized constant #{ full_name }")
end