Class: Toil::Prototype

Inherits:
Object
  • Object
show all
Defined in:
lib/toil/prototype.rb

Constant Summary collapse

CALLBACKS =
%i[after_create before_create].freeze
NO_ATTS_MSG =
'There are no attribute arguments for this prototype.'.freeze
AlreadyRegistered =
Class.new(ArgumentError)
NoAttributesDefined =
Class.new(RuntimeError)
NotRegistered =
Class.new(ArgumentError)
@@registry =
{}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(constructor, arguments = [], callbacks = {}, &blk) ⇒ Prototype

Returns a new instance of Prototype.



31
32
33
34
35
36
# File 'lib/toil/prototype.rb', line 31

def initialize(constructor, arguments = [], callbacks = {}, &blk)
  @constructor = __constructor__(constructor)
  @arguments = __arguments__(arguments)
  @callbacks = __callbacks__(callbacks)
  instance_eval(&blk) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &blk) ⇒ Object



42
43
44
# File 'lib/toil/prototype.rb', line 42

def method_missing(m, *args, &blk)
  @arguments.public_send(m, *args, &blk)
end

Class Method Details

.[](key) ⇒ Object

Raises:



16
17
18
19
20
# File 'lib/toil/prototype.rb', line 16

def [](key)
  raise NotRegistered, "`:#{key}` is not a registered prototype" unless
    @@registry.key?(key)
  @@registry[key]
end

.register(key, obj = nil, &blk) ⇒ Object

Raises:



22
23
24
25
26
27
28
# File 'lib/toil/prototype.rb', line 22

def register(key, obj = nil, &blk)
  key = key.to_sym
  raise AlreadyRegistered, "`:#{key}` has already been registered" if
    @@registry.key?(key)

  @@registry[key] = obj.is_a?(Symbol) ? self[obj].dup(&blk) : new(obj, &blk)
end

Instance Method Details

#call(*overrides) ⇒ Object



38
39
40
# File 'lib/toil/prototype.rb', line 38

def call(*overrides)
  __exec_callbacks__(:after_create, @constructor.(*to_a(*overrides)))
end

#dup(&blk) ⇒ Object



46
47
48
# File 'lib/toil/prototype.rb', line 46

def dup(&blk)
  self.class.new(@constructor, @arguments, @callbacks, &blk)
end

#to_a(*overrides) ⇒ Object Also known as: to_ary



50
51
52
# File 'lib/toil/prototype.rb', line 50

def to_a(*overrides)
  __exec_callbacks__(:before_create, @arguments.to_a(*overrides))
end

#to_h(overrides = {}) ⇒ Object Also known as: to_hash



55
56
57
58
59
60
# File 'lib/toil/prototype.rb', line 55

def to_h(overrides = {})
  raise NoAttributesDefined, NO_ATTS_MSG unless (at = @arguments.attributes_at)
  args = @arguments.to_a
  args[at].merge!(overrides)
  __exec_callbacks__(:before_create, args)[at]
end