Module: Tins::FromModule

Includes:
ParameterizedModule
Included in:
Module
Defined in:
lib/tins/dslkit.rb

Overview

A module that provides parameterized module creation capabilities.

This module enables the creation of new modules by filtering methods from existing modules, allowing for flexible composition and interface segregation at runtime.

Examples:

class MixedClass
  extend Tins::FromModule

  include MyModule     # has foo, bar and baz methods
  include from module: MyIncludedModule, methods: :foo
  include from module: MyIncludedModule2, methods: :bar
end

c = MixedClass.new
assert_equal :foo,  c.foo # from MyIncludedModule
assert_equal :bar2, c.bar # from MyIncludedModule2
assert_equal :baz,  c.baz # from MyModule

Create a stack-like class using Array methods

class Stack < Class.from(module: Array, methods: %i[ push pop last ])
end

s = Stack.new
s.push(1)
s.push(2)
s.last  # => 2
s.pop   # => 2
s.last  # => 1

Instance Method Summary collapse

Methods included from ParameterizedModule

#parameterize_for

Instance Method Details

#parameterize(opts = {}) ⇒ Module

Creates a new module by filtering methods from an existing module.

This method duplicates the specified module and removes all methods except those explicitly listed in the :methods option. This enables creating specialized interfaces from existing modules.

Parameters:

  • opts (Hash) (defaults to: {})

    Configuration options

Options Hash (opts):

  • :module (Module) — default: required

    The source module (or class) to filter methods from

  • :methods (Array<Symbol>) — default: required

    Array of method names to preserve

Returns:

  • (Module)

    A new module with only the specified methods available



913
914
915
916
917
918
919
920
921
922
923
924
925
926
# File 'lib/tins/dslkit.rb', line 913

def parameterize(opts = {})
  modul = opts[:module] or raise ArgumentError, 'option :module is required'
  import_methods = Array(opts[:methods])
  result = modul.dup
  remove_methods = modul.instance_methods.map(&:to_sym) - import_methods.map(&:to_sym)
  remove_methods.each do |m|
    begin
      result.__send__ :remove_method, m
    rescue NameError
      # Method might already be removed or not exist
    end
  end
  result
end