class Object

Public Instance Methods

interface(&block) click to toggle source

The interface method creates an interface module which typically sets a list of methods that must be defined in the including class or module. If the methods are not defined, an Interface::MethodMissing error is raised.

A interface can extend an existing interface as well. These are called sub-interfaces, and they can included the rules for their parent interface by simply extending it.

Example:

# Require 'alpha' and 'beta' methods
AlphaInterface = interface{
   required_methods :alpha, :beta
}

# A sub-interface that requires 'beta' and 'gamma' only
GammaInterface = interface{
   extends AlphaInterface
   required_methods :gamma
   unrequired_methods :alpha
}

# Raises an Interface::MethodMissing error because :beta is not defined.
class MyClass
   def alpha
      # ...
   end
   implements AlphaInterface
end
# File lib/interface.rb, line 96
def interface(&block)
  Module.new do |mod|
    mod.extend(Interface)
    mod.instance_eval(&block)
  end
end