Accessing your Application Classes (including models) in Rake Tasks

When writing Rake tasks, to get access to all classes (such as the User model in this example) in your app’s environment, you need to depend on the :environment task shown as follows:

  task :post_user => :environment  do
    end_time = Time.new
    start_time = end_time - 60 #subtract 60 seconds
    until start_time > end_time
      start_time = start_time + 15 #increment 15 seconds
      puts "Posting #{start_time}"
      uesr = User.new(:user_id => 817, :timestamp => start_time)
      user.save
    end
  end
Share