Skip to content

Instantly share code, notes, and snippets.

@mattwynne
Forked from stevecj/defines_interface.rb
Created October 11, 2012 19:22
Show Gist options
  • Save mattwynne/3874873 to your computer and use it in GitHub Desktop.
Save mattwynne/3874873 to your computer and use it in GitHub Desktop.
Interfaces for Ruby
# total pseudocode
class StickyNotePlacer < Role
messages :call, :user, :message, :color?
end
class ApplicationApi < Role
messages :sticky_note_placer
end
module Application
def self.new
Base.new
end
class Base
as_role(ApplicationApi) do
def sticky_note_placer
ConsoleStickyNotePlacer.new
end
end
end
class ConsoleStickyNotePlacer
as_role(StickyNotePlacer) do
def call(user, message, color = :yellow)
puts "#{self} called with #{[user, message, color]}"
end
end
end
end
# This would fail on line 27, because the as_role call would notice that not all the messages
# for the StickyNotePlacer role had been defined by ConsoleStickyNotePlacer.
# If you did define those methods too, then the thing should work.
#
# The point is that the roles act a bit like Java interfaces, and allow you to explicitly
# partition up polymorphic behaviour of a class.
#
# The also allow you to get some checking as to whether you're conforming to the role's protocol
# when you make an implementation.
#
# WDYT?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment