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.



23
24
25
26
27
# File 'lib/dry/core/extensions.rb', line 23

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



41
42
43
# File 'lib/dry/core/extensions.rb', line 41

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



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

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



33
34
35
# File 'lib/dry/core/extensions.rb', line 33

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