Select object based on date range - ruby-on-rails

Tech specs: ruby 2.1.5p273, Rails 4.2.3.
I have an array of Days that I want to loop through to pick the right Exits (model) that fall within a date range.
#exits has :start_date and :end_date
#days is an array of dates like:
=> [Sun, 06 Sep 2015, Sat, 12 Sep 2015, Tue, 15 Sep 2015, Fri, 18 Sep 2015, Sat, 19 Sep 2015, Sun, 20 Sep 2015, Wed, 23 Sep 2015]
I thought something like this would work:
#days.each do |day|
#exits.where(:start_date..:end_date).include?(day)
end
but I get an error:
TypeError: Cannot visit Range
What is the best way to query an object that has a date range (between two fields) by comparing it against a single date? Thanks!

You can use the following:
#days.each do |day|
exits = Exit.where('? BETWEEN start_date AND end_date', day)
# etc.
end

If you don't want to loop over them then you can do:
Event.where("start_date IN (:days) AND end_date IN (:days)", { days: #days })
or
Event.where(start_date: #days, end_date: #days)

Exit.where(day: #exit.start_date..#exits.end_date)
or
Exit.where('day >= ? AND day <= ?', #exit.start_date, #exits.end_date)
Doing SQL queries in a loop is probably a bad idea, it could be refactored to be be one call most likely. And this should happen in the controller not in the view.

Related

Finding days between 2 days in Ruby on Rails

I am facing some problem in finding the days between 2 dates.
The scenario is as follow :
time = Time.new
enddate_timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
startdate = #logInfo.updated_at #here updated_at is the column in the db .
What is the best way to find the days ?
Post.where(["date(created_at) BETWEEN ? AND ?", Date.yesterday, Date.tomorrow]
More details: http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where
There are several possible solutions. A possibility is to create a Range with the dates, then convert the range into an array
# set the boundaries
today = Time.current
past = 5.days.ago
Note that both boundaries are time instances. We should cast them into dates. I used time(s) because your column is a time.
range = past.to_date..today.to_date
# => Sun, 29 Dec 2013..Fri, 03 Jan 2014
Use to_a to expand the range getting all the days
range.to_a
# => [Sun, 29 Dec 2013, Mon, 30 Dec 2013, Tue, 31 Dec 2013, Wed, 01 Jan 2014, Thu, 02 Jan 2014, Fri, 03 Jan 2014]
range.count
# => 6
You can also enumerate them
range.each { |day| puts day.day }
29
30
31
1
2
3
now = Time.now
future = Time.now + 100 days
while now < future
now = now + 1.day
puts now
end
This will give you the dates, not the days count.
(startdate.beginning_of_day..enddate_timestamp.to_time.beginning_of_day).step(1.day) do |day|
puts day
end
P.S: Performance wise it's not good.

rails helper function to return the most recent date

I need to Write rails helper method to return the most recent date.
So far this is my method
def latest_date(value_dates)
value_dates.each |value_date| do
my_dates << value_date
end
I need to sort the above array and return just the latest date.
The date is in the following format:
2012-10-10T22:11:52.000Z
Is there a sort method for date?
The .max method will do it for you ;)
> [Date.today, (Date.today + 2.days) ].max
#=> Fri, 05 Jul 2013
Documentation about it (Ruby 2.0):
http://ruby-doc.org/core-2.0/Enumerable.html#method-i-max
You may need to parse the data into Dates, if they are strings, you can use:
dates = ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"]
dates = dates.map{ |date_str| Date.parse(date_str) }
dates.max #=> returns the maximum date of the Array
See in my irb console (Ruby 1.9.3):
> dates = ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"]
#=> ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"]
> dates = dates.map{ |date_str| Date.parse(date_str) }
#=> [Wed, 10 Oct 2012, Sat, 10 Nov 2012, Thu, 10 Oct 2013]
> dates.max
#=> Thu, 10 Oct 2013
(use DateTime.parse(date_str) if you want to keep the Time also)

How can I use a Date object and a string with a day name to create a new Date object?

I have a Date object
Mon, 03 Dec 2012
and I have a String that contains a day name
"Thursday"
How can I use those two objects to find a new Date object representing the day name in the same week as the original Date object? So for this example, it would be
Thu, 07 Dec 2012
In this scenario, a week goes from Monday to Sunday.
I'm using Rails 3.2.0 and Ruby 1.9.3.
If you can manage to convert "Thursday" to week day 4 -- I know you can --, you can get another date like this:
1.9.3p125 :014 > d = Date.parse "Mon, 03 Dec 2012"
=> Mon, 03 Dec 2012
1.9.3p125 :015 > Date.commercial d.cwyear, d.cweek, 4
=> Thu, 06 Dec 2012
1.9.3p125 :016 >
BTW, you can store the map from day name to number in an Array or an Hash, or use I18n.
I am sure there is a better way for doing this but you could do
def date_by_day(date, day_name)
beginning_of_week = date.beginning_of_week
7.times do |i|
_date = beginning_of_week + i.days
return _date if _date.strftime("%A") == day_name
end
end
This one will work nicely for you.
def date_by_day(date, day_name)
beginning_of_week = date.beginning_of_week
day_number = Time::DAYS_INTO_WEEK[day_name.to_sym]
return (beginnig_of_week + day_number.days)
end

Given a DateTime, how do I get the range of times with the same date in a particular time zone?

I have a DateTime object representing a particular date, as in "2011-01-15 00:00:00 UTC" to represent January 15th. I would like to produce the range of times in a particular time zone that have the same date.
The method signature would probably be something like
def day_range_for(date, tz)
# ...
end
For example, if I have range_for(DateTime.parse('2011-01-15'), 'CST'), then I want the result to be a range like 2011-01-15 00:00:00 -0600 .. 2011-01-15 23:59:59 -0600.
Can you take the input string instead of the object? If you pass in a DateTime object, its a tad counter intuitive because the time the object represents isn't the actual time you are looking for. It would conform to my expectations if you either passed in the correct, absolute DateTime, or the string itself. The actual meat of the problem is entirely handled by ActiveSupport, which I think you are using since you tagged this question with Rails. How does this look?
def range_for(input, tz=nil)
if tz.is_a?(String)
tz = ActiveSupport::TimeZone.new(tz)
else
tz = Time.zone
end
if input.acts_like?(:date) || input.acts_like?(:time)
d = input.in_time_zone(tz)
else
d = tz.parse(input)
end
return d.beginning_of_day..d.end_of_day
end
Have a look:
ruby-1.9.2-p0 > range_for('2011-01-15', 'Alaska')
=> Sat, 15 Jan 2011 00:00:00 AKST -09:00..Sat, 15 Jan 2011 23:59:59 AKST -09:00
ruby-1.9.2-p0 > range_for(Time.zone.now)
=> Mon, 10 Jan 2011 00:00:00 EST -05:00..Mon, 10 Jan 2011 23:59:59 EST -05:00
ruby-1.9.2-p0 > range_for('2011-01-15', 'EST')
=> Sat, 15 Jan 2011 00:00:00 EST -05:00..Sat, 15 Jan 2011 23:59:59 EST -05:00
How about:
def day_range_for date, zone
(DateTime.new(date.year,date.month,date.day,0,0,0,zone)..DateTime.new(date.year,date.month,date.day,23,59,59,zone))
end
day_range_for(DateTime.parse('2011-01-15'), 'CST')
#=> #<DateTime: 2011-01-15T00:00:00-06:00 (9822307/4,-1/4,2299161)>..#<DateTime: 2011-01-15T23:59:59-06:00 (212161917599/86400,-1/4,2299161)>

Is it possible to create a list of months between two dates in Rails

I am trying to create a page to display a list of links for each month, grouped into years. The months need to be between two dates, Today, and The date of the first entry.
I am at a brick wall, I have no idea how to create this.
Any help would be massively appriciated
Regards
Adam
Just put what you want inside a range loop and use the Date::MONTHNAMES array like so
(date.year..laterdate.year).each do |y|
mo_start = (date.year == y) ? date.month : 1
mo_end = (laterdate.year == y) ? laterdate.month : 12
(mo_start..mo_end).each do |m|
puts Date::MONTHNAMES[m]
end
end
The following code will add a months_between instance method to the Date class
#!/usr/bin/ruby
require 'date'
class Date
def self.months_between(d1, d2)
months = []
start_date = Date.civil(d1.year, d1.month, 1)
end_date = Date.civil(d2.year, d2.month, 1)
raise ArgumentError unless d1 <= d2
while (start_date < end_date)
months << start_date
start_date = start_date >>1
end
months << end_date
end
end
This is VERY lightly tested, however it returns an Array of dates each date being the 1st day in each affected month.
I don't know if I've completely understood your problem, but some of the following might be useful. I've taken advantage of the extensions to Date provided in ActiveSupport:
d1 = Date.parse("20070617") # => Sun, 17 Jun 2007
d2 = Date.parse("20090529") #=> Fri, 29 May 2009
eom = d1.end_of_month #=> Sat, 30 Jun 2007
mth_ends = [eom] #=> [Sat, 30 Jun 2007]
while eom < d2
eom = eom.advance(:days => 1).end_of_month
mth_ends << eom
end
yrs = mth_ends.group_by{|me| me.year}
The final line uses another handy extension: Array#group_by, which does pretty much exactly what it promises.
d1.year.upto(d2.year) do |yr|
puts "#{yrs[yr].min}, #{yrs[yr].max}"
end
2007-06-30, 2007-12-31
2008-01-31, 2008-12-31
2009-01-31, 2009-05-31
I don't know if the start/end points are as desired, but you should be able to figure out what else you might need.
HTH
Use the date_helper gem which adds the months_between method to the Date class similar to Steve's answer.
xmas = Date.parse("2013-12-25")
hksar_establishment_day = Date.parse("2014-07-01")
Date.months_between(xmas,hksar_establishment_day)
=> [Sun, 01 Dec 2013, Wed, 01 Jan 2014, Sat, 01 Feb 2014, Sat, 01 Mar 2014, Tue, 01 Apr 2014, Thu, 01 May 2014, Sun, 01 Jun 2014, Tue, 01 Jul 2014]

Resources