Module: Shoryuken::Helpers::StringUtils

Defined in:
lib/shoryuken/helpers/string_utils.rb

Overview

Utility methods for string manipulation.

This module provides helper methods for common string operations that were previously implemented as core class extensions. By using a dedicated helper module, we avoid polluting the global namespace while maintaining the same functionality.

Examples:

Basic usage

klass = Shoryuken::Helpers::StringUtils.constantize('MyWorker')
# => MyWorker

Class Method Summary collapse

Class Method Details

.constantize(string) ⇒ Class, Module

Converts a string to a constant.

This method takes a string representation of a constant name and returns the actual constant. It handles nested constants (e.g., ‘Foo::Bar’) and leading double colons (e.g., ‘::Object’). This is commonly used for dynamically loading worker classes from configuration.

Examples:

Converting a simple class name

StringUtils.constantize('String')
# => String

Converting a nested constant

StringUtils.constantize('Shoryuken::Worker')
# => Shoryuken::Worker

Handling leading double colon

StringUtils.constantize('::Object')
# => Object

Worker class loading

worker_class = StringUtils.constantize('MyApp::EmailWorker')
worker_instance = worker_class.new

Error handling

begin
  StringUtils.constantize('NonExistentClass')
rescue NameError => e
  puts "Class not found: #{e.message}"
end

Parameters:

  • string (String)

    The string to convert to a constant

Returns:

  • (Class, Module)

    The constant represented by the string

Raises:

  • (NameError)

    if the constant is not found or not defined



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/shoryuken/helpers/string_utils.rb', line 50

def constantize(string)
  names = string.split('::')
  names.shift if names.empty? || names.first.empty?

  constant = Object

  names.each do |name|
    constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
  end

  constant
end