Module: Interface

Defined in:
lib/interface.rb,
lib/interface/version.rb,
lib/interface/abstract.rb,
lib/interface/test_helper.rb

Overview

Implementable interfaces in ruby

Defined Under Namespace

Modules: Abstract, TestHelper, Version

Instance Method Summary collapse

Instance Method Details

#implements(*modules) ⇒ Object Also known as: implement

Takes a module (or multiple in reverse order), extends it with Interface::Abstract, then includes it into the current object

Example

module Remote
  # turns the device on
  def on
  end
end

class Device
  implements Remote

  def on
    @power = true
  end
end


24
25
26
# File 'lib/interface.rb', line 24

def implements(*modules)
  modules.flatten.reverse!.each { |mod| include mod.extend(Abstract) }
end

#interfacesObject

Returns an array of interfaces implemented by the current object



32
33
34
35
# File 'lib/interface.rb', line 32

def interfaces
  klass = is_a?(Class) ? self : self.class
  klass.included_modules.select { |mod| mod.is_a?(Abstract) }
end

#respond_to?(method, include_private = false) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


53
54
55
# File 'lib/interface.rb', line 53

def respond_to?(method, include_private = false) # :nodoc:
  super || respond_to_missing?(method, include_private)
end

#respond_to_missing?(method, include_private) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


57
58
59
# File 'lib/interface.rb', line 57

def respond_to_missing?(method, include_private) # :nodoc:
  false
end

#unimplemented_methodsObject

Returns a hash with each partially implemented interface as keys and an array of methods that the current object does not implement as values



39
40
41
42
43
44
# File 'lib/interface.rb', line 39

def unimplemented_methods
  self.class.interfaces.inject({}) do |hash, interface|
    methods = unimplemented_methods_for(interface)
    methods.empty? ? hash : hash.merge!(interface => methods)
  end
end

#unimplemented_methods_for(interface) ⇒ Object

Returns an array of methods from the specified interface that the current object does not implement



47
48
49
# File 'lib/interface.rb', line 47

def unimplemented_methods_for(interface)
  interface.instance_methods(false).reject { |method| respond_to_missing?(method.to_sym, true) || self.method(method.to_sym).owner != interface }.sort
end