Skip to content

Instantly share code, notes, and snippets.

@wconrad
Created December 20, 2018 21:27
Show Gist options
  • Save wconrad/dbb7a0a713b715b31c93f3159ff7d9cd to your computer and use it in GitHub Desktop.
Save wconrad/dbb7a0a713b715b31c93f3159ff7d9cd to your computer and use it in GitHub Desktop.
OOP greetings example for Mirv in Ruby SO chat
class TimeRange
def initialize(start_hour, stop_hour)
@start_hour = start_hour
@stop_hour = stop_hour
end
def complete?
@start_hour && @stop_hour
end
def include?(hour)
return false unless complete?
(@start_hour..@stop_hour).include?(hour)
end
end
class Greeting
def self.from_hash(h)
message = h.fetch(:message)
time_range = TimeRange.new(h.fetch(:start), h.fetch(:stop))
new(message, time_range)
end
def initialize(message, time_range)
@message = message
@time_range = time_range
end
def in_effect?(hour)
@time_range.include?(hour)
end
end
class Greetings
def self.from_array_of_hashes(a)
a.map do |h|
Greeting.from_hash(h)
end
end
def initialize(greetings)
@greetings = greetings + [default_greeting]
end
def find(hour)
@greetings.find do |greeting|
greeting.in_effect?(hour)
end
end
private
def default_greeting
Greeting.new("Greetings!", TimeRange.new(0, 24))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment