Skip to content

Instantly share code, notes, and snippets.

@fdavidcl
Last active April 23, 2017 15:35
Show Gist options
  • Save fdavidcl/e6a02273e78019d96137 to your computer and use it in GitHub Desktop.
Save fdavidcl/e6a02273e78019d96137 to your computer and use it in GitHub Desktop.
Implementation for Java-like Interfaces in Ruby
#!/usr/bin/env ruby
#encoding: utf-8
############ Interface code
class InterfaceClass < Module
private
def included(klass)
if klass != Object
@_implemented.each do |m|
if !klass.method_defined?(m)
raise NoMethodError.new("method '#{m}' from Interface '#{self}' not implemented for #{klass}")
end
end
end
end
def initialize(*methods, &interface)
@_implemented = methods.flatten
interface.call if !interface.nil?
end
public
def child(*methods, &interface)
self.class.new(@_implemented + methods) do
interface.call if !interface.nil?
end
end
end
Interface = InterfaceClass.new
############ End interface code
############ Test code
OneInterface = Interface.child(:one_method, :method_too) do
GRAVITY = 9.81
end
ExampleInterface = OneInterface.child(:third_method)
class SomeClass
def one_method
puts GRAVITY
end
def method_too
puts "2"
end
include ExampleInterface # --> method 'third_method' from Interface 'ExampleInterface' not implemented for SomeClass
end
############ End test code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment