Skip to content

Instantly share code, notes, and snippets.

@shirts
Last active October 7, 2019 18:15
Show Gist options
  • Save shirts/6548f8ea60ba0a3d3a5718d73299dff4 to your computer and use it in GitHub Desktop.
Save shirts/6548f8ea60ba0a3d3a5718d73299dff4 to your computer and use it in GitHub Desktop.
Abstract Interface
module AbstractInterface
class InterfaceNotImplementedError < NoMethodError
end
def self.included(base)
base.send(:include, AbstractInterface::Methods)
base.send(:extend, AbstractInterface::Methods)
base.send(:extend, AbstractInterface::ClassMethods)
end
module Methods
def api_not_implemented(klass, name)
raise AbstractInterface::InterfaceNotImplementedError.new("#{klass.class.name} needs to implement '#{name}' for interface #{self.name}!")
end
end
module ClassMethods
def needs_implementation(klass, method_name, *args)
self.class_eval do
define_method(method_name) do |*args|
klass.api_not_implemented(self, method_name)
end
end
end
end
end
class Bicycle
include AbstractInterface
needs_implementation self, :change_gear, :new_value
needs_implementation self, :brake
end
class MountainBike < Bicycle
def change_gear(new_value)
puts "Gear changed to #{new_value}"
end
end
class Mammal
include AbstractInterface
needs_implementation self, :walk, :steps
needs_implementation self, :breathe
needs_implementation self, :cry
end
class Human < Mammal
def walk(steps = 2)
puts "Walking #{steps} steps"
end
def breathe
puts "Inhales slowly"
end
end
begin
mb = MountainBike.new
mb.change_gear(2)
mb.brake
rescue StandardError => e
puts e
end
begin
h = Human.new
h.walk(10)
h.breathe
h.cry
rescue StandardError => e
puts e
end
=begin
Gear changed to 2
MountainBike needs to implement 'brake' for interface Bicycle!
Walking 10 steps
Inhales slowly
Human needs to implement 'cry' for interface Mammal!
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment