class Toil::Prototype

Constants

AlreadyRegistered
CALLBACKS
NO_ATTS_MSG
NoAttributesDefined
NotRegistered

Public Class Methods

[](key) click to toggle source
# File lib/toil/prototype.rb, line 16
def [](key)
  raise NotRegistered, "`:#{key}` is not a registered prototype" unless
    @@registry.key?(key)
  @@registry[key]
end
new(constructor, arguments = [], callbacks = {}, &blk) click to toggle source
# 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
register(key, obj = nil, &blk) click to toggle source
# 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

Public Instance Methods

call(*overrides) click to toggle source
# File lib/toil/prototype.rb, line 38
def call(*overrides)
  __exec_callbacks__(:after_create, @constructor.(*to_a(*overrides)))
end
dup(&blk) click to toggle source
# File lib/toil/prototype.rb, line 46
def dup(&blk)
  self.class.new(@constructor, @arguments, @callbacks, &blk)
end
method_missing(m, *args, &blk) click to toggle source
# File lib/toil/prototype.rb, line 42
def method_missing(m, *args, &blk)
  @arguments.public_send(m, *args, &blk)
end
to_a(*overrides) click to toggle source
# File lib/toil/prototype.rb, line 50
def to_a(*overrides)
  __exec_callbacks__(:before_create, @arguments.to_a(*overrides))
end
Also aliased as: to_ary
to_ary(*overrides)
Alias for: to_a
to_h(overrides = {}) click to toggle source
# 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
Also aliased as: to_hash
to_hash(overrides = {})
Alias for: to_h

Private Instance Methods

__arguments__(args) click to toggle source
# File lib/toil/prototype.rb, line 69
def __arguments__(args)
  args.is_a?(Arguments) ? args.dup : Arguments.new(args)
end
__callbacks__(callbacks) click to toggle source
# File lib/toil/prototype.rb, line 73
def __callbacks__(callbacks)
  CALLBACKS.each_with_object({}) { |k, h| h[k] = [] }.merge(callbacks)
end
__constructor__(obj) click to toggle source
# File lib/toil/prototype.rb, line 77
def __constructor__(obj)
  raise ArgumentError, 'Object does not respond to `call`' unless obj.respond_to?(:call)
  obj
end
__exec_callbacks__(key, args) click to toggle source
# File lib/toil/prototype.rb, line 82
def __exec_callbacks__(key, args)
  @callbacks[key].each { |clbk| clbk.(args) }
  args
end