Created
November 23, 2015 17:21
-
-
Save glaucocustodio/b48e06ca12707d6825c8 to your computer and use it in GitHub Desktop.
Rails helper that returns if current time is contained in a time range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def current_time_between start_time, end_time | |
now = Time.now | |
start_time = start_time.split(':') | |
end_time = end_time.split(':') | |
start_time_hour = start_time.first.to_i | |
start_time_min = start_time.last.to_i | |
end_time_hour = end_time.first.to_i | |
end_time_min = end_time.last.to_i | |
(now.hour == start_time_hour ? now.min >= start_time_min : now.hour > start_time_hour) && (now.hour == end_time_hour ? now.min <= end_time_min : now.hour < end_time_hour) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "spec_helper" | |
describe ApplicationHelper do | |
include ActiveSupport::Testing::TimeHelpers | |
describe "#current_time_between" do | |
context 'returns true' do | |
it do | |
puts '8:05' | |
travel_to Time.new(2004, 11, 24, 8, 05, 00) do | |
expect(current_time_between('08:05', '19:50')).to be(true) | |
end | |
end | |
it do | |
(9..19).each do |hour| | |
puts "#{hour}:00" | |
travel_to Time.new(2004, 11, 24, hour, 00, 00) do | |
expect(current_time_between('08:05', '19:50')).to be(true) | |
end | |
end | |
end | |
it do | |
puts '19:50' | |
travel_to Time.new(2004, 11, 24, 19, 50, 00) do | |
expect(current_time_between('08:05', '19:50')).to be(true) | |
end | |
end | |
end | |
context 'returns false' do | |
it do | |
puts '19:51' | |
travel_to Time.new(2004, 11, 24, 19, 51, 00) do | |
expect(current_time_between('08:05', '19:50')).to be(false) | |
end | |
end | |
it do | |
(20..23).each do |hour| | |
puts "#{hour}:00" | |
travel_to Time.new(2004, 11, 24, hour, 00, 00) do | |
expect(current_time_between('08:05', '19:50')).to be(false) | |
end | |
end | |
end | |
it do | |
(0..8).each do |hour| | |
puts "#{hour}:00" | |
travel_to Time.new(2004, 11, 24, hour, 00, 00) do | |
expect(current_time_between('08:05', '19:50')).to be(false) | |
end | |
end | |
end | |
it do | |
puts '08:04' | |
travel_to Time.new(2004, 11, 24, 8, 04, 00) do | |
expect(current_time_between('08:05', '19:50')).to be(false) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment