Created
July 19, 2019 08:19
-
-
Save rmcsharry/03a6f62ad0cfaa68957ac68acd93b809 to your computer and use it in GitHub Desktop.
A factory with no if statements inspired by Sandi Metz "Polly want a message" talk
This file contains 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
class Clump | |
def initialize(spec:, input:) | |
@spec = spec | |
@possibilities = @input | |
end | |
def self.build(spec:, possibilities: []) | |
descendants.detect { |klass| klass.match?(spec) }.new(spec: spec, input: possibilities).lines | |
end | |
def self.inherited?(klass) | |
descendants.push klass | |
end | |
def self.descendants | |
@descendants ||= [] | |
end | |
end | |
class Comment < Clump | |
def self.match?(spec) | |
spec.include?('#') | |
end | |
def lines | |
#...etc... | |
end | |
end | |
class LineNumber < Clump | |
def self.match?(spec) | |
true | |
end | |
def lines | |
#...etc... | |
end | |
private | |
def expand_clump | |
#...etc... | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sandi Metz gave a great presentation about OO design and polymorphism, using a Factory to refactor some code.
It inspired me to find a way to improve the Factory and remove the if statements completely.
This gist and the great article that goes with it were a help, most especially the posted by @mereghost.
Ref: https://apidock.com/ruby/v1_9_3_125/Class/inherited