-
-
Save mattwynne/3874873 to your computer and use it in GitHub Desktop.
Interfaces for Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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