Evaluating points in time by months, but without referencing years in Rails - ruby-on-rails

FYI, There is some overlap in the initial description of this question with a question I asked yesterday, but the question is different.
My app has users who have seasonal products. When a user selects a product, we allow him to also select the product's season. We accomplish this by letting him select a start date and an end date for each product.
We're using date_select to generate two sets of drop-downs: one for the start date and one for the end date.
Including years doesn't make sense for our model. So we're using the option: discard_year => true
When you use discard_year => true, Rails sets a year in the database, it just doesn't appear in the views. Rails sets all the years to either 0001 or 0002 in our app. Yes, we could make it 2009 and 2010 or any other pair. But the point is that we want the months and days to function independent of a particular year. If we used 2009 and 2010, then those dates would be wrong next year because we don't expect these records to be updated every year.
My problem is that we need to dynamically evaluate the availability of products based on their relationship to the current month. For example, assume it's March 15. Regardless of the year, I need a method that can tell me that a product available from October to January is not available right now.
If we were using actual years, this would be pretty easy.
For example, in the products model, I can do this:
def is_available?
(season_start.past? && season_end.future?)
end
I can also evaluate a start_date and an end_date against current_date
However, in setup I've described above where we have arbitrary years that only make sense relative to each other, these methods don't work. For example, is_available? would return false for all my products because their end date is in the year 0001 or 0002.
What I need is a method just like the ones I used as examples above, except that they evaluate against current_month instead of current_date, and past? and future months instead of years.
I have no idea how to do this or whether Rails has any built in functionality that could help. I've gone through all the date and time methods/helpers in the API docs, but I'm not seeing anything equivalent to what I'm describing.
Thanks.

Set the year of the current date to 1000 and perform a range compare with the start and end dates.
def is_available?
t = Date.today
d = Date.new(1000, t.month, t.day)
(season_start..season_end).include?(d) or
(season_start..season_end).include?(d+1.year)
end
Second comparison above is to address the following scenario:
Lets say today Jan 15 and the season is from Oct - Feb. In our logic, we set the date to Jan 15 1000. This date will not be within Oct 1 1000 - Mar 1 1001. Hence we do the second comparison where we advance the date by a year to Jan 15 1001, which is within the range.

You might want to consider not using Date objects. What if season_start_month and season_end_month were each an integer 1-12, set with your dropdown? Then when doing your is_available? comparison, you could dynamically create the full date for season_start, doing some math for transitions over December to January. This could use some refactoring, and isn't tested, but should do the trick. Assumes that season_start_month and season_end_month are integers stored in this model:
class Product < ActiveRecord::Base
def is_available?
now = Time.now
season_start < now && now < season_end
end
def season_start
now = Time.now
current_month = now.month
season_start_year = season_start_month < current_month ? now.year : now.year - 1
Time.local(season_start_year, season_start_month)
end
def season_end
now = Time.now
current_month = now.month
season_end_year = season_end_month > current_month ? now.year : now.year + 1
Time.local(season_end_year, season_end_month)
end
end

Related

Sidekiq to perform action for last month and end of current month

I have this logic into my head but find it difficult to put into code; I can but not sure when to perform this action with Sidekiq
Compare last month's expenses with this month's expenses (end of this calendar month)
Worker Class:
def perform(*args) # params left out for this example
[...]
last_month = user.expenses.where(date: 1.month.ago) # ie Jan
this_month = user.expenses.where(date: Date.today.at_beginning_of_month..Date.today.end_of_month) # ie Feb (end of Feb)
# Then my if else here
end
Controller:
CompareExpenseWorker.perform_in(...)
I am stuck there. When should this perform? In 1 or 2 months?
I feel my mind is playing games on me. If I perform in 1 month, I will only get last month but not the current month ( full calendar month). If performed in 2 months, I feel that's not correct. Is it?
In the first place, the calculation for the last_month should be:
# last_month = user.expenses.where(date: 1.month.ago) # incorrect
last_month = user.expenses.where(
date: 1.month.ago.beginning_of_month..1.month.ago.end_of_month)
I believe, the whole logic should be changed, though. If you want to compare two full months, it should be done as:
month_2 = user.expenses.where( # e.g. Feb
date: 2.month.ago.beginning_of_month..2.month.ago.end_of_month)
month_1 = user.expenses.where( # e.g. Mar
date: 1.month.ago.beginning_of_month..1.month.ago.end_of_month)
# run at any day in April, to compare two full months
# user_id is the id of the user to build reports for
CompareExpenseWorker.perform(user_id)
Furthermore, I don’t think the call to CompareExpenseWorker should be put into controller, use cronjob for that, scheduled at 1st of every month.

Rails - change default time in Time datatype

In my view, I will be ordering a list of items by their start_time. There are instances, however, where there might be a start_time of 1:00 AM (the following day) that should show up as after a start_time of 11:00 PM (previous day). Since the Time datatype stores a default date of 2001-01-01, it considers an entry of 1:00 AM to be on 2001-01-01, not 2001-01-02.
Thus, my question is, is there a way to change the default date in the Time datatype?
I suppose an obvious solution would be to instead store the start and end times in a DateTime datatype and enter a corresponding date. For this application, however, it is customary to refer to a start time of 1:00 AM as "belonging to" the previous day and would thus be confusing to enter the following day's date. (E.g. When attending your favorite band's concert on a Friday night, their set might start at 12:30 am Saturday morning, but you would still consider the concert to be on a Friday night). Thank you for your help.
Not a direct answer to your question, but a possible solution to your problem: you could create a custom sort that sorts times < 1 AM last.
sorted_concerts = Concert.order('CASE WHEN start_time <= "2001-01-01 01:00:00" THEN 2 ELSE 1 END, start_time')
This way you can leave the db columns as is but get your expected order for concerts. Excepting for this 1 AM inversion, the times will sort normally in ascending order.
After much more research, it doesn't seem like the default date of "2001-01-01" that Ruby applies to a time stored in a Time datatype can be adjusted. I guess this answers my question - but - to solve the problem, I changed the db columns to datetime datatype and logged a default date, that would adjust if the time entry was after midnight. Controller action below:
def create
start_time = DateTime.parse("#{run_of_show_item_params[:date]} #{run_of_show_item_params[:start_time]}")
end_time = DateTime.parse("#{run_of_show_item_params[:date]} #{run_of_show_item_params[:end_time]}")
#run_of_show_item = RunOfShowItem.new(run_of_show_item_params)
#run_of_show_item.start_time = start_time
#run_of_show_item.end_time = end_time
#run_of_show_item.start_time+=1.days if run_of_show_item_params[:start_time] < "07:00"
#run_of_show_item.end_time+=1.days if run_of_show_item_params[:start_time] < "07:00"
if #run_of_show_item.save
flash[:success] = "Performance added!"
redirect_to :back
else
render 'new'
end
end

Rails - define custom year

I need to define a custom month range as a project_year.
Rather than a year starting in January and ending at the end of December, I need to define a project_year as starting August 1st and ending on the last day of July.
I need to group all reports by project_year and then by month. Report has a report_month attribute(dateTime). Essentially I would need to display the reports like this:
Projects:
2015
August
September
October
November
Etc
2014
August
September
October
November
Etc
2013
August
September
October
November
Etc
I've been playing around with the Array.sample method, but without success.
reports = #station.reports.order("report_month asc")
range = reports.last.report_month.year..reports.first.report_month.year
range.to_a.each do |year|
start = year.beginning_of_year + 7.months
finish = (year.beginning_of_year + 1.year - 6.months).end_of_month
yr = reports.sample{ |r| report.report_month >= start and <= finish }
<h1><%= year.strftime("%Y")</h1>
yr.each do |m|
<h1><%= m.strftime("%b")</h1>
end
end
I realize the above isnt appropriate view code, Im just trying to indicate the manner I was trying to use. Which became cumbersome and hard to troubleshoot. After struggling with this for a while I decided to ask here.
Ultimately my the ideal would be to use the group_by feature outlined here:
http://railscasts.com/episodes/29-group-by-month Only instead using group_by project_year.
Is this possible with Rails? Or is there a better way to group by a custom month range?
Does it help if you add a the customer field on the model such as quarter then use the group_by api.
def quarter
"#{created_at.month/4}, #{created_at.year}"
end

Rails 3, comparing only the dates of two datetime columns in rails

Lets say I want to compare the dates only of two datetime columns within 1 record. So I don't want the time looked at.
I.e.
viewed_date, and updated_at (I added viewed_date) are two datetime formats, but I only want to see if they occurred on the same day or days apart. The problem with datetime is that its comparing the times, which is just too specific for me right now.
Thanks
-Elliot
Declare a new attribute that contains just the date:
class WhateverModel < ActiveRecord::Base
...
def viewed_date_only
viewed_date.to_date
end
end
Use that for your comparison in the controller or wherever.
You can compare only date of object without comparing time like this:-
start_date :-"2015-04-06 15:31:43 +0530"
end_date :- "2015-04-16 15:31:43 +0530 "
post_review.all.where("(created_at::date >= :start_date) AND
(created_at::date <= :end_date)", start_date: start_date.strftime("%Y-%m-%d"),end_date: end_date.strftime("%Y-%m-%d"))
Above query gets all the records made between 6 to 16 April

Given a date, how can I efficiently calculate the next date in a given sequence (weekly, monthly, annually)?

In my application I have a variety of date sequences, such as Weekly, Monthly and Annually. Given an arbitrary date in the past, I need to calculate the next future date in the sequence.
At the moment I'm using a sub-optimal loop. Here's a simplified example (in Ruby/Rails):
def calculate_next_date(from_date)
next_date = from_date
while next_date < Date.today
next_date += 1.week # (or 1.month)
end
next_date
end
Rather than perform a loop (which, although simple, is inefficient especially when given a date in the distant past) I'd like to do this with date arithmetic by calculating the number of weeks (or months, years) between the two dates, calculating the remainder and using these values to generate the next date.
Is this the right approach, or am I missing a particularly clever 'Ruby' way of solving this? Or should I just stick with my loop for the simplicity of it all?
Because you tagged this question as ruby-on-rails, I suppose you are using Rails.
ActiveSupport introduces the calculation module which provides an helpful #advance method.
date = Date.today
date.advance(:weeks => 1)
date.advance(:days => 7)
# => next week
I have used the recurrence gem in the past for this purpose. There are a few other gems that model recurring events listed here.
If you are using a Time object, you can use Time.to_a to break the time into an array (with fields representing the hour, day, month, etc), adjust the appropriate field, and pass the array back to Time.local or Time.utc to build a new Time object.
If you are using the Date class, date +/- n will give you a date n days later/earlier, and date >>/<< n will give you a date n months later/earlier.
You can use the more generic Date.step instead of your loop. For example,
from_date.step(Date.today, interval) {|d|
# Each iteration of this block will be passed a value for 'd'
# that is 'interval' days after the previous 'd'.
}
where interval is a length of time in days.
If all you are doing is calculating elapsed time, then there is probably a better approach to this. If your date is stored as a Date object, doing date - Date.today will give you the number of days between that date and now. To calculate months, years, etc, you can use something like this:
# Parameter 'old_date' must be a Date object
def months_since(old_date)
(Date.today.month + (12 * Date.today.year)) - (old_date.month + (12 * old_date.year))
end
def years_since(old_date)
Date.today.year - old_date.year
end
def days_since(old_date)
Date.today - old_date
end

Resources