Module: Tins::RequireMaybe

Included in:
Object
Defined in:
lib/tins/require_maybe.rb

Overview

A module that provides a safe require mechanism with optional error handling.

This module is included in Object, making the ‘require_maybe` method globally available throughout your Ruby application. It enables conditional loading of libraries where the failure to load a dependency is not necessarily an error condition, making it ideal for optional dependencies and feature detection.

Examples:

Basic usage anywhere in your codebase

# Available globally:
require_maybe 'foo'  # Returns true/false

Providing fallback behavior

class MyParser
  def parse_data(data)
    if require_maybe('foo')
      Foo::Parser.parse(data)
    else
      Bar.parse(data)  # Fallback
    end
  end
end

With error handling block

require_maybe 'some_gem' do |error|
  puts "Optional gem 'some_gem' not available: #{error.message}"
end

Instance Method Summary collapse

Instance Method Details

#require_maybe(library) {|LoadError| ... } ⇒ Boolean

Attempts to require a library, gracefully handling LoadError exceptions.

This method is globally available because the module is included in Object. It’s particularly useful for optional dependencies and feature detection.

Parameters:

  • library (String)

    The name of the library to require

Yields:

  • (LoadError)

    Optional block to handle the LoadError

Yield Parameters:

  • error (LoadError)

    The rescued LoadError exception

Returns:

  • (Boolean)

    Returns true if library was loaded successfully, false otherwise



39
40
41
42
43
# File 'lib/tins/require_maybe.rb', line 39

def require_maybe(library)
  require library
rescue LoadError => e
  block_given? and yield e
end