Skip to content

Instantly share code, notes, and snippets.

@malakai97
Last active April 23, 2019 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malakai97/cef73aaafdc6a4984b7f221b50d54100 to your computer and use it in GitHub Desktop.
Save malakai97/cef73aaafdc6a4984b7f221b50d54100 to your computer and use it in GitHub Desktop.
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