Class: Toritori::Factory

Inherits:
Object
  • Object
show all
Defined in:
lib/toritori/factory.rb

Overview

Generates module that adds support for objects creation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, base_class: nil, creation_method: :new, &block) ⇒ Factory

Returns a new instance of Factory.



12
13
14
15
16
# File 'lib/toritori/factory.rb', line 12

def initialize(name, base_class: nil, creation_method: :new, &block)
  @name = name
  @base_class = base_class
  @creation_method = block || creation_method
end

Instance Attribute Details

#base_classObject (readonly)

Returns the value of attribute base_class.



6
7
8
# File 'lib/toritori/factory.rb', line 6

def base_class
  @base_class
end

#creation_methodObject (readonly)

Returns the value of attribute creation_method.



6
7
8
# File 'lib/toritori/factory.rb', line 6

def creation_method
  @creation_method
end

Instance Method Details

#copyObject



8
9
10
# File 'lib/toritori/factory.rb', line 8

def copy
  self.class.new(@name, base_class: @base_class, creation_method: @creation_method)
end

#create(*args, **kwargs, &block) ⇒ Object



24
25
26
27
28
29
# File 'lib/toritori/factory.rb', line 24

def create(*args, **kwargs, &block)
  return @creation_method.call(*args, **kwargs, &block) if defined? @creation_method.call
  return @base_class.new(*args, **kwargs, &block) if @creation_method == :new

  @base_class.public_send(@creation_method, *args, **kwargs, &block)
end

#subclass(produces: nil, creation_method: @creation_method, &block) ⇒ Object



18
19
20
21
22
# File 'lib/toritori/factory.rb', line 18

def subclass(produces: nil, creation_method: @creation_method, &block)
  @base_class = check_base_class(produces) || @base_class
  @base_class = Class.new(@base_class, &block) if block
  @creation_method = creation_method
end