Ruby - slice array and copy date values - ruby-on-rails

Pretty new to Ruby, I am having trouble implementing some logic
I have a lot of dates (effective and expiration dates).
I also have 2 objects. An original object, and a new copied object (it is a copy of the original)
I want to loop through each pair of dates, and check the orignal objects dates fields to see if ti had any. If it did have dates, then I was to:
use the original objects expiration date as the new objects effective date
default the new objects expiration date to the new effective date + 1 year
Here is my code, I get this error:
undefined method `id' for nil:NilClass
CODE:
DATE_FIELDS = [:agency_effective_on, :agency_expire_on,
:field_effective_on, :field_expire_on,
:product_manager_effective_on, :product_manager_expire_on,
:officer_effective_on, :officer_expire_on,
:regional_officer_effective_on, :regional_officer_expire_on]
#copy_to = #copy_from.dup
DATE_FIELDS.each.slice(2) do |field|
if !#copy_from.send(field[0].to_sym).nil? #if the ORIGNAL date is not nil
#copy it to the new Objects dates
#copy_to.send("#{field[0]}=".to_sym, #copy_from.send(field[0]))
#copy_to.send("#{field[1]}=".to_sym, #copy_from.send(field[1]).to_date + 365)
end
end

Ok so I had each.slice instead of each_slice

Related

Validate date range exist in array

I have an array of object. Every object have a start_date and and end_date (DATETIME).
I save it with : #arroy_of_objects.each(&:save)
But I can't have two date in the same time. If a start_date is equal and between an another date range, I don't want to save it.
How can I do it with rails ? In a validate in the model or directly in my controller

ROR: How to get and compare just the dates of datetimes using SQL query

I want to be able to list any 'events' in my database which occur on the same date as another event being creating in my method.
The column I want to compare is 'starts_at' and is a DateTime.
How can I just compare the date that events occured on instead of both date and time?
I need to add the query to this where call:
events = Event.where(location_id: location.id)
I already have a date object date to compare to, I just don't know how I can get just the date part of the events already in the database?
is it something along the lines of date(starts_at:)?
events = Event.where(location_id: location.id, date(starts_at:): date)
I am using sqlite database.
Check if this works with your DB or not:
events = Event.where(location_id: location.id).where("DATE(starts_at) = ?", date)
OR, compare in datetime as per active record:
events = Event.where(location_id: location.id,starts_at: date.beginning_of_day..date.end_of_day)

Unexplained ArgumentError try to load date from string

Rails 4.1
I'm am trying to add a date attribute to an ActiveRecord object by handing it a string and I'm getting some strange results:
t = MyClass.new
t.StartDate = "1/11/2015" #date is loaded as expected
t.StartDate = "1/12/2015" #date is loaded as expected
t.StartDate = "1/13/2015" #ArgumentError: argument out of range
The same appears to hold true for any day of the month > 12. What am I missing here? Yes, I could parse the string into a Date object (and I've been able to do this successfully with the same problem dates as strings), but why does my method work for some valid dates and not others?
Your dates are formatted with day/month/year when your trying to use it like month/day/year
This is why you can't go further than 12 because 12 is representing the month

Check if the value is in range between closest array's elements. (ruby)

I need to know how would I check if my given value is between two closest array's members. For example I have an array of dates with the date of week start in given period of time. And I need to check if my given date is in one of its week. For example:
2015-11-02
2015-11-09
2015-11-16
2015-11-23
And my given value is 2015-11-11 for example. How should I check if it is one of these weeks date? Thanks for help.
%w(2015-11-02 2015-11-09 2015-11-16 2015-11-23).any? do |date|
date.to_date.cweek == Date.today.cweek
end
And here is what this does:
First, you have an array of strings, you use any? to loop through it and check if any fulfils a requirement, then you cast you date strings into actual dates, and cweek gives you the number of a week in the year. Date.today gives you today's date.
Instead of Date.today.cweek you can use '2015-11-11'.to_date.cweek.
The loop above returns boolean; you could also get an array of values that fulfil a condition like this:
new_array = %w(2015-11-02 2015-11-09 2015-11-16 2015-11-23).map do |date|
date.to_date.cweek == '2015-11-11'.to_date.cweek
end.compact
Resources:
Date class on ruby-doc.org
Date & Time in Ruby on tutorialspoint.com
UPDATE
If you want to get from the database only records with a date from particular week, this is how you could do it:
my_date = '2015-11-11'.to_date
matching_records = MyResource.where( date: my_date.beginning_of_week..my_date.end_of_week )
The assumptions are that you have a model MyResource, and that it has a column date. What this does is returns a relation with all the records that have dates from the same week as my_date.
Assuming your dates array is sorted:
date >= dates.first && date <= dates.last
If you're dealing with strings, you can "require 'date'" and transform your strings to dates ("Date.parse('2001-02-03')").
As others have suggested, you can then see if your date is between the first and last entry of your list.
If the real list is sorted and each entry is one week apart, then you can easily find where in the list your guy is.
E.g., say the list is [date_0, date_1, date_2, ..., date_k] (all 1 week apart), and you're given a test_date between date_0 and date_k. Then (test_date.jd - date_0.jd)/7 gives you the index of the date in your list that is <= test_date.

Generating a random date without time in Ruby

I have a date of birth column on my user table that takes a DATE. As this datatype appears as YYYY-MM-DD, I assume that when inputting a date to the database it must have the format, for example: 2013-12-26.
I have seen methods on StackOverflow for creating a random DateTime in Ruby, such as here. However, after much searching I can't find a way to generate a random date without the time, for example in the past 100 years, and have it properly formatted for the DATE datatype. In Rails, what is the best way to generate a random date without the time?
This seems to work:
def rand_date(days)
date = Date.today-rand(days)
date.to_s(:db)
end
But is there a more elegant solution that comes with Rails? I am new to Rails and programming, so any assistance would be most helpful!
Your method is correct. If you are using Rails, there are some trivial improvements such as
def rand_date(days)
rand(days).days.ago(Date.today)
end
which is mostly equivalent to
def rand_date(days)
rand(days).days.ago.to_date
end
The second version is less efficient because it creates more Date/Time objects during the internal conversions.
Apply to_s(:db) if you need the Date to be formatted as String.
A different approach would require you to construct a date passing the result of a rand to Date.new.
This is in core ruby:
1 #!usr/bin/ruby
2
3 require 'date'.
4
5 10.times do |t|
6 random_year = Random.new.rand(2000..2014) # custom range for years
7 random_month =Random.new.rand(1..12)
8 random_day = Random.new.rand(1..30)
9 puts "#{Date.new(random_year,random_month,random_day)}"
10 end
2014-11-29
2010-10-20
2006-02-23
2009-09-17
2006-01-14
2009-01-06
2002-07-06
2005-11-05
2013-06-20
2005-12-02
Here is something I used to generate random birth dates when populating a customer database. It works on days, and in this example, gives random dates between 1967-01-09 and 1993-01-12 by using the Date#jd method:
Date.jd(2439500 + rand(9500))
You can twiddle the dates generated by setting the base (in this case 2439500, which is 1967-01-09) and the random number to increase or decrease the range of dates produced.
Example:
irb(main):043:0> 10.times { puts Date.jd(2439500 + rand(9500)) }
1973-06-07
1973-11-09
1983-07-27
1990-11-03
1967-06-18
1967-06-20
1970-07-28
1990-05-13
1986-11-26
1989-02-15

Resources