Andrew
Andrew

Reputation: 159

Using the Ruby on Rails 'upto' method in a Rake task

I have the following rake task which automatically generates a daily post, or if a user has no posts it will generate all the posts automatically retroactively to their start date:

namespace :abc do
desc "Used to generate a new daily log"
task :create_post => :environment do

User.find_each do |currentUser|
  starting_date = currentUser.start_date
  if Date.today >= starting_date && Date.today.on_weekday?
    if currentUser.posts.count.zero?
      starting_date.upto(Date.today) { |date| currentUser.generate_post if date.on_weekday? }
    else
      currentUser.generate_post
    end
  end
end
puts "It actually worked yo!"
end
end

I'm attempting to achieve the retroactive generation of posts with the 'upto' method however when I run the code as its written I get the following error:

NoMethodError: undefined method `upto' for Tue, 09 May 2017 21:42:54 UTC +00:00:Time
C:/Users/vanbeeandr/workspace/online_journal/lib/tasks/create_post.rake:14:in `block (3 levels) in <top (required)>'
 C:/Users/vanbeeandr/workspace/online_journal/lib/tasks/create_post.rake:7:in `block (2 levels) in <top (required)>'
   NoMethodError: undefined method `upto' for 2017-05-09 21:42:54 UTC:Time
C:/Users/vanbeeandr/workspace/online_journal/lib/tasks/create_post.rake:14:in `block (3 levels) in <top (required)>'
 C:/Users/vanbeeandr/workspace/online_journal/lib/tasks/create_post.rake:7:in `block (2 levels) in <top (required)>'
  Tasks: TOP => abc:create_post
  (See full trace by running task with --trace)

I feel like my rake task is written correctly so I'm not sure why this error is being thrown. Can anyone help with this?

Upvotes: 0

Views: 247

Answers (2)

Andrew
Andrew

Reputation: 159

I solved this by adding .to_datetime to my above code as follows:

starting_date = currentUser.start_date.to_datetime

Upvotes: 0

xlts
xlts

Reputation: 136

Actually, the error says that start_date is a Time instance. Ruby/Rails only allow to loop through instances of Date and DateTime (see Iterate over Ruby Time object with delta).

Upvotes: 1

Related Questions