Skip to content

Instantly share code, notes, and snippets.

@rmcsharry
Created July 19, 2019 08:19
Show Gist options
  • Save rmcsharry/03a6f62ad0cfaa68957ac68acd93b809 to your computer and use it in GitHub Desktop.
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
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
@rmcsharry
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment