Skip to content

Instantly share code, notes, and snippets.

@IanWhitney
Created March 15, 2015 02:20
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 IanWhitney/2a6ffb08520d50794d78 to your computer and use it in GitHub Desktop.
Save IanWhitney/2a6ffb08520d50794d78 to your computer and use it in GitHub Desktop.
class Bob
def reply_to(statement)
statement.reply(self)
rescue
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
def reply(recipient)
recipient.reply_to_question
end
end
class Yelling < Statement
def self.match?(statement)
statement.upcase == statement && statement.downcase != statement
end
def reply(recipient)
recipient.reply_to_yelling
end
end
class Silence < Statement
def self.match?(statement)
statement.strip.empty?
end
def reply(recipient)
recipient.reply_to_silence
end
end
class NullStatement < Statement
def self.match?(statement)
true
end
def reply(recipient)
recipient.default_reply
end
end
class StatementFactory
def self.build(statement)
Statements.all.detect { |s| s.match?(statement) }.new(statement)
end
end
y = StatementFactory.build("HELLO")
q = StatementFactory.build("HELLO?")
s = StatementFactory.build("")
d = StatementFactory.build("hello")
Bob.new.reply_to(y)
#=> "Woah, chill out!"
Bob.new.reply_to(q)
#=> "Sure"
Bob.new.reply_to(s)
#=> "Fine. Be that way!"
Bob.new.reply_to(d)
#=> "Whatever."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment