Skip to content

Instantly share code, notes, and snippets.

@OliDM
Forked from IanWhitney/final_bob.rb
Last active August 29, 2015 14:16
Show Gist options
  • Save OliDM/47e13094828d92e58f2e to your computer and use it in GitHub Desktop.
Save OliDM/47e13094828d92e58f2e to your computer and use it in GitHub Desktop.
Removing conditionals in favor of multiple subclasses
class Bob
def reply_to(statement)
public_send("reply_to_#{statement.class}".downcase.to_sym)
rescue NoMethodError
default_reply
end
def reply_to_silence
"Fine. Be that way!"
end
def reply_to_yelling
"Woah, chill out!"
end
def reply_to_question
"Sure."
end
def default_reply
"Whatever."
end
end
class Statements
def self.all
[Question, Yelling, Silence, NullStatement]
end
end
Statement = Struct.new(:statement)
class Question < Statement
def self.match?(statement)
statement.end_with?("?")
end
end
class Yelling < Statement
def self.match?(statement)
statement.upcase == statement && statement.downcase != statement
end
end
class Silence < Statement
def self.match?(statement)
statement.strip.empty?
end
end
class NullStatement < Statement
def self.match?(statement)
true
end
end
class StatementFactory
def self.build(statement)
Statements.all.detect { |s| s.match?(statement) }.new(statement)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment