Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including rails datetime helper in custom rake task

I want to create a rake task to fill the details of product but the product has to be random in order to format be able to sort it later on based on the date. I would like to include the datehelper provided by the framework in it but I dont seem to have idea on this. How can this be done. My custom rake task looks like this;

namespace :db do
desc "Filling the data with  products"
  task :fill_products do 
    [{:name => "1 Galon milk", :price => 2.99, :released => Time.now.to_datetime},
    {:name => "Oh's Cereal'", :price => 3.95, :released => 1.year.ago},
    {:name => "Red T-Shirt", :price => 12.49, :released => 2.years.ago},
    {:name => "Settler's of Catan'", :price => 29.95, :released => 2.months.ago},
    {:name => "Video Game Disc", :price => 29.95, :released => 5.moths.ago},
    {:name => "DVD Player", :price => 79.99, :released => 88.days.ago},
    {:name => "Oak Coffee Table", :price => 223.99, :released => 499.days.ago},
    {:name => "Video Game Console", :price => 299.95, :released => 982.days.ago},
    {:name => "Black Leather Couch", :price => 399.99, :released => 1092.days.ago}
    ].each do |attr|
      Product.create!(attr)
    end
  end
end

But as I run the rake command for the task, it gives me error as undefined method 'year' for 1:Fixnum, I suppose this error is due to the fact that it does not have access to the date helper methods provided by rails. So how can I include the helper to enable the support.

like image 793
Sandeep Avatar asked Dec 06 '25 10:12

Sandeep


1 Answers

Try to make your task dependent on the :environment Rails' task:

task :fill_products => :environment do
  # ...
end

and let's see what happens...

like image 96
Aldo 'xoen' Giambelluca Avatar answered Dec 08 '25 23:12

Aldo 'xoen' Giambelluca