Module: SleepingKingStudios::Tools::Toolbox::Subclass

Defined in:
lib/sleeping_king_studios/tools/toolbox/subclass.rb

Overview

Mixin for partially applying constructor parameters.

Examples:

class Character
  extend SleepingKingStudios::Tools::Toolbox::Subclass

  def initialize(*traits)
    @traits = traits
  end

  attr_reader :traits
end

Bard = Character.subclass(:charismatic, :musical)

aoife = Bard.new(:sorcerous)
aoife.traits
#=> [:charismatic, :musical, :sorcerous]

Instance Method Summary collapse

Instance Method Details

#subclass(*class_arguments, **class_keywords) { ... } ⇒ Class

Creates a subclass with partially applied constructor parameters.

Parameters:

  • class_arguments (Array)

    The arguments, if any, to apply to the constructor. These arguments will be added before any args passed directly to the constructor.

  • class_keywords (Hash)

    The keywords, if any, to apply to the constructor. These keywords will be added before any kwargs passed directly to the constructor.

Yields:

  • The block, if any, to pass to the constructor. This will be overriden by a block passed directly to the constructor.

Returns:

  • (Class)

    the generated subclass.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/sleeping_king_studios/tools/toolbox/subclass.rb', line 38

def subclass(*class_arguments, **class_keywords, &class_block) # rubocop:disable Metrics/MethodLength
  subclass = Class.new(self)

  subclass.define_method :initialize do |*args, **kwargs, &block|
    super(
      *class_arguments,
      *args,
      **class_keywords,
      **kwargs,
      &(block || class_block)
    )
  end

  subclass
end