Class: Object

Inherits:
BasicObject
Defined in:
lib/interface.rb

Instance Method Summary collapse

Instance Method Details

#interface(&block) ⇒ Object

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


97
98
99
100
101
102
# File 'lib/interface.rb', line 97

def interface(&block)
  mod = Module.new
  mod.extend(Interface)
  mod.instance_eval(&block)
  mod
end