Module: Dry::Core::Extensions

Defined in:
lib/dry/core/extensions.rb

Overview

Define extensions that can be later enabled by the user.

Examples:


class Foo
  extend Dry::Core::Extensions

  register_extension(:bar) do
     def bar; :bar end
  end
end

Foo.new.bar # => NoMethodError
Foo.load_extensions(:bar)
Foo.new.bar # => :bar

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(obj) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



25
26
27
28
29
# File 'lib/dry/core/extensions.rb', line 25

def self.extended(obj)
  super
  obj.instance_variable_set(:@__available_extensions__, {})
  obj.instance_variable_set(:@__loaded_extensions__, Set.new)
end

Instance Method Details

#available_extension?(name) ⇒ Boolean

Whether an extension is available

Parameters:

  • name (Symbol)

    extension name

Returns:

  • (Boolean)

    Extension availability



43
44
45
# File 'lib/dry/core/extensions.rb', line 43

def available_extension?(name)
  @__available_extensions__.key?(name)
end

#load_extensions(*extensions) ⇒ Object

Enables specified extensions. Already enabled extensions remain untouched

Parameters:

  • extensions (Array<Symbol>)

    list of extension names



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dry/core/extensions.rb', line 50

def load_extensions(*extensions)
  extensions.each do |ext|
    block = @__available_extensions__.fetch(ext) do
      raise ArgumentError, "Unknown extension: #{ext.inspect}"
    end
    unless @__loaded_extensions__.include?(ext)
      block.call
      @__loaded_extensions__ << ext
    end
  end
end

#register_extension(name) { ... } ⇒ Object

Register an extension

Parameters:

  • name (Symbol)

    extension name

Yields:

  • extension block. This block guaranteed not to be called more than once



35
36
37
# File 'lib/dry/core/extensions.rb', line 35

def register_extension(name, &block)
  @__available_extensions__[name] = block
end