Skip to content

Instantly share code, notes, and snippets.

@malakai97 malakai97/elsewhere.rb
Last active Apr 23, 2019

Embed
What would you like to do?
Ruby #handles? style factories
Superclass.for(obj) # => The concrete subclass instance you wanted
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
require "superclass"
class Subclass < Superclass
register(self)
def self.handles(target)
# return a boolean
end
end
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
You can’t perform that action at this time.