Last active
April 23, 2019 17:25
-
-
Save malakai97/cef73aaafdc6a4984b7f221b50d54100 to your computer and use it in GitHub Desktop.
Ruby #handles? style factories
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
Superclass.for(obj) # => The concrete subclass instance you wanted |
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
module Registered | |
def for(target) | |
registry.find {|candidate| candidate.handles?(target) } | |
.new(target) | |
end | |
def registry | |
@@registry ||= [] # rubocop:disable Style/ClassVars | |
end | |
def register(candidate) | |
registry.unshift(candidate) | |
end | |
def handles?(_target) | |
true | |
end | |
end |
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
require "superclass" | |
class Subclass < Superclass | |
register(self) | |
def self.handles(target) | |
# return a boolean | |
end | |
end | |
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
require "registered" | |
class Superclass | |
extend Registered | |
register(self) # Because this will always be evaluated first, it serves as a default. | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment