Class: Plumbing::RubberDuck

Inherits:
Object
  • Object
show all
Defined in:
lib/plumbing/rubber_duck.rb,
lib/plumbing/rubber_duck/proxy.rb,
lib/plumbing/rubber_duck/module.rb,
lib/plumbing/rubber_duck/object.rb

Overview

A type-checker for duck-types

Defined Under Namespace

Classes: Proxy

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*methods) ⇒ RubberDuck

Returns a new instance of RubberDuck.



8
9
10
11
# File 'lib/plumbing/rubber_duck.rb', line 8

def initialize *methods
  @methods = methods.map(&:to_sym)
  @proxy_classes = {}
end

Class Method Details

.cast(object, type:) ⇒ Object

Cast the object to the given type

Parameters:



40
41
42
# File 'lib/plumbing/rubber_duck.rb', line 40

def cast object, type:
  type.proxy_for object
end

.define(*methods) ⇒ Object

Define a new rubber duck type

Parameters:

  • *methods (Array<Symbol>)

    the methods that the duck-type should respond to



33
34
35
# File 'lib/plumbing/rubber_duck.rb', line 33

def define *methods
  new(*methods)
end

Instance Method Details

#proxy_for(object) ⇒ Boolean

Test if the given object is a proxy

Parameters:

  • object (Object)

    the object to test

Returns:

  • (Boolean)

    true if the object is a proxy, false otherwise



26
27
28
# File 'lib/plumbing/rubber_duck.rb', line 26

def proxy_for object
  is_a_proxy?(object) || build_proxy_for(object)
end

#verify(object) ⇒ Object

Verify that the given object responds to the required methods

Parameters:

  • object (Object)

    the object to verify

Returns:

  • (Object)

    the object if it passes the verification

Raises:

  • (TypeError)

    if the object does not respond to the required methods



17
18
19
20
21
# File 'lib/plumbing/rubber_duck.rb', line 17

def verify object
  missing_methods = @methods.reject { |method| object.respond_to? method }
  raise TypeError, "Expected object to respond to #{missing_methods.join(", ")}" unless missing_methods.empty?
  object
end