module Interface

A module for implementing Java style interfaces in Ruby. For more information about Java interfaces, please see:

java.sun.com/docs/books/tutorial/java/concepts/interface.html

Constants

VERSION

The version of the interface library.

Public Instance Methods

required_methods(*ids) click to toggle source

Accepts an array of method names that define the interface. When this module is included/implemented, those method names must have already been defined.

# File lib/interface.rb, line 51
def required_methods(*ids)
  @ids = ids
end
unrequired_methods(*ids) click to toggle source

Accepts an array of method names that are removed as a requirement for implementation. Presumably you would use this in a sub-interface where you only wanted a partial implementation of an existing interface.

# File lib/interface.rb, line 59
def unrequired_methods(*ids)
  @unreq ||= []
  @unreq += ids
end

Private Instance Methods

append_features(mod) click to toggle source
Calls superclass method
# File lib/interface.rb, line 23
def append_features(mod)
  return super if Interface === mod

  # Is this a sub-interface?
  inherited = (self.ancestors-[self]).select{ |x| Interface === x }
  inherited = inherited.map{ |x| x.instance_variable_get('@ids') }

  # Store required method ids
  ids = @ids + inherited.flatten
  @unreq ||= []

  # Iterate over the methods, minus the unrequired methods, and raise
  # an error if the method has not been defined.
  (ids - @unreq).uniq.each do |id|
    unless mod.instance_methods(true).include?(id)
      raise Interface::MethodMissing, id
    end
  end

  super mod
end
extend_object(obj) click to toggle source
# File lib/interface.rb, line 17
def extend_object(obj)
  return append_features(obj) if Interface === obj
  append_features(class << obj; self end)
  included(obj)
end