Module: Taipo::Result::ClassMethods Private

Defined in:
lib/taipo/result.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

A helper module for holding the DSL methods

Since:

  • 1.5.0

Instance Method Summary collapse

Instance Method Details

#result(method_name, type) ⇒ Object

The DSL method used to declare a type check on the return value of a method. The intention is that a user will declare the type of result expected from a method by calling this method in the body of a class definition.

For purposes of readability, the convention is that #result will be called near the beginning of the class definition but this is not a requirement and the user is free to call the method immediately before or after the relevant method definition.

Examples:

require 'taipo'

class A
  include Taipo::Result

  result :foo, 'String'
  result :bar, 'Integer'

  def foo(arg)
    arg.to_s
  end

  def bar(arg)
    arg.to_s
  end
end

a = A.new
a.foo 'Hello world!'  #=> "Hello world!"
a.bar 42              #=> Taipo::TypeError

Parameters:

  • method_name (Symbol)

    the name of the instance method

  • type (String)

    a type definition

Since:

  • 1.5.0



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/taipo/result.rb', line 82

def result(method_name, type)
  base = self
  checker = const_get "#{base.class.name}Checker"
  checker.class_eval do
    define_method(method_name) do |*args, &block|
      method_return_value = super(*args, &block)
      if Taipo::Utilities.match?(object: method_return_value,
                                 definition: type)
        method_return_value
      else
        Taipo::Utilities.throw_error(object: method_return_value,
                                     name: "#{base.name}##{method_name}",
                                     definition: type,
                                     result: true)
      end
    end
  end
end