I want to show a greeting message through out the day. If it's 12 am through 11:59 am i want a good morning message and so on. This is what i have but cant seem to get it working.
def greet if Time.now <= Time.now.beginning_of_day render :text =>"Good Morning" elsif Time.now <= Time.now.middle_of_day render :text => "Good Afternoon" elsif Time.now <= Time.now.change(:hour => 5 ) render :text => "Good Evening" elsif Time.now <= Time.now.change(:hour => 8 ) render :text =>"Good Night" end end
I will be displaying something like this in my views.
<# This should display a greeting to the user %> <%= greet %> <%= current_user.name %>
First, let's make the time a bit easier to read. I set the five variables below based on your conditions. I also convert these to epoch time via
to_i
current_time = Time.now.to_i midnight = Time.now.beginning_of_day.to_i noon = Time.now.middle_of_day.to_i five_pm = Time.now.change(:hour => 17 ).to_i eight_pm = Time.now.change(:hour => 20 ).to_i
You can then use your
if conditions to display the correct text (or render as you had it).
if midnight.upto(noon).include?(current_time) puts "Good Morning" elsif noon.upto(five_pm).include?(current_time) puts "Good Afternoon" elsif five_pm.upto(eight_pm).include?(current_time) puts "Good Evening" elsif eight_pm.upto(midnight + 1.day).include?(current_time) puts "Good Night" end
Or, you can move away from
if statements and use
case.
case when midnight.upto(noon).include?(current_time) puts "Good Morning" when noon.upto(five_pm).include?(current_time) puts "Good Afternoon" when five_pm.upto(eight_pm).include?(current_time) puts "Good Evening" when eight_pm.upto(midnight + 1.day).include?(current_time) puts "Good Night" end
Personally, what you had works, but you're not creating true definitions of the boundaries. While this may not be a big deal, I do like having definitive boundaries set just in case something happens down the road which could cause problems.