How to run only rake task once - ruby-on-rails

I am using Ruby on Rails and Heroku.
I would like something like rake db:migrate, where it will only run the parts that have not been run before.
I can set a rake task that can run other rake task, but is there in way to only run those that did not run before?
What are any alternative, if I want rake tasks to be run automatically?

first of, running a rake task twice, ie rake db:migrate will neither duplicate nor overwrite your database columns if they already exist.
For example capistrano, used to deploy your rails app to basically anywhere, will rerun tasks like db:migrateor assets:precompile every time you deploy your app. So no need to worry about that really.
To run tasks automatically you will need something like a cron job. Whenever is a great ruby gem that allows you to install a job like this with the beloved ruby syntax.
After installing the gem and running wheneverize . in the root of your rails app, you may edit the scheduler.rb and add something like:
every :sunday, :at => '12pm' do
rake my:awesome:task
end
The Github page as well as the default scheduler.rb hold many useful examples of how these jobs are built.
with whenever --update-crontab you can write your rubyesque cronjobs into the crontab, which will run your tasks periodically at the time you want them to.
** edit
multiple tasks in one:
task :setup => [:a, :b, :c]
task :a do
%x(bash command)
end
task :b do
rake db:migrate
end
task :c do
rake whatever
end

Related

Rails 5 scheduler to update database once a day

I'm new to rails and want to run a batch file/schedule task daily once at midnight that checks which entries have expired. Every record in the table has a closing_date and after that time, such records must be inactive.(status active=false on DB). so basically it will run 2 SQL queries to fetch all records and then flag another field to inactive for records that are outdated.I'm working with Rails 5.
How should I go about this-gem(rufus,whatever,clockwork or any other gem) or simply some system tool for cronjob?I'm going to change my DB to PostgreSQL so will that impact? Any suggestions or sample code anyone can share to get an idea.
In brief: You can use whenever Gem for this purpose.
You need to create a rake task for where you will write your SQL.
Then schedule it as cron job using whenever
Detailed explanation
First step will be creating a rake task. You can do this using the console
rails g task my_namespace my_task1
This will create a file named my_namespace.rake in the lib/tasks folder with initial content like
namespace :my_namespace do
desc "TODO"
task task1: :environment do
# Your code will go here
end
end
You can check whether your task is running properly by running
rake my_namespace:task1
in the console.
Now you need to schedule the job using the whenever gem.
gem 'whenever', :require => false in Gemfile.
Run bundle install
run wheneverize command in terminal. This will create a schedule.rb file in config folder .
Add the following code to schedule your rake task:
every 1.day, at: '8:00 pm' do
rake "my_namespace:task1"
end
Run this command: whenever --update-crontab. In case your environment is development, use command: whenever --update-crontab --set environment='development' (see this question.
run crontab -l to check whether cron job has been added.

Rails - Run Rake tasks with Capistrano

Im scratching my head here wondering if I'm barking up the wrong tree. I have a server which I've deployed a Rails app onto using Capistrano. Recently I added a new data type to one of the models, and now I need to run a Rake task to update the existing records.
After a lot of Googling I'm starting to wonder if people use Rake tasks with Capistrano. Some forum posts from 2013 or so mention that Capistrano supports the .rake extension. Whereas other posts I've found indicate that Capistrano has its own task automation system, and is incompatible with rake.
I found Cape, but I'm unsure if this is what I'm looking for as it seems to convert Rake tasks into cap recipes. Its possible I'm mistaken on this point, I really don't have any experience working with Capistrano or even working in the full stack spectrum.
What I'm wondering is this: How do I run a simple Rake task on my remote server?
Some quick points for clarity, I've installed the app on the latest Ubuntu LTS, 14.10 if memory serves. I followed the tutorial found here. I have full sudo access and I can ssh into the server.
thanks in advance for helping a noob
If you need to update models, you can of course write a Rails migration - this will ensure that it's run if it hasn't been run yet.
The easiest way to execute a rake task on the server would be just via ssh if it's a one-time task. See the last paragraph in the tutorial you mentioned:
cd /opt/www/testapp/current ; bin/rake RAILS_ENV=production db:seed
To answer your original question about rake: you can execute rake tasks via capistrano similar to how you would execute it locally, only within the capistrano script. Here's an example:
deploy.rb:
namespace :rake do
desc "My task"
task :my_task do
on roles(:app) do
within "#{current_path}" do
with rails_env: :production do
execute :rake, "my_task"
# !!!see NOTE at end of answer!!!
end
end
end
end
end
You can view all your cap tasks via cap -T locally. The capistrano task I wrote above should show up as cap tasks:my_rake_task.
If you want to be ably to run any available rake task without configuring, do the following:
namespace :rake do
desc "Invoke rake task"
task :invoke do
on roles(:app) do
within "#{current_path}" do
with rails_env: :production do
execute :rake, ENV['task']
# !!!see NOTE at end of answer!!!
end
end
end
end
end
Then you can write:
cap production deploy:invoke task=my:rake:task
NOTE: you might want to replace the execution line with
run "bin/rake RAILS_ENV=#{rails_env} #{ENV['task']}"
to use the same syntax as the tutorial (without the binstubs you might need to configure capistrano/bundler and capistrano/rbenv first ...)
Check out capistrano-rake
Once installed, run any rake task on your production/staging servers without messy capistrano recipes by simply doing this:
$ cap production invoke:rake TASK=your:rake:task
Full Disclosure: I wrote it

How do I execute a "rake task" after every db:reset

I'm working on a personal project and I have a strange doubt. At the localhost, I do rake db:reset almost every time and I always need to run another task named newsworker:create (in other words, I run rake newsworker:create).
My questions are:
How can I execute a specific rake task after every rake db:reset?
How can I generalize the above question to work with rake db:create and other tasks?
Thanks!
In my opinion, the best way is to create your own rake task calling all the tasks needed (to avoid changing Rails/Rake basic tasks):
# lib/tasks/reset_and_create
namespace :database do
desc 'Reset the database to a fresh and clean DB ready for use'
task :reset_and_create do
Rake::Task['db:reset'].invoke
Rake::Task['newsworker:create'].invoke
# if you need to pass arguments to your tasks, use:
# Rake::Task['your_task'].invoke(your_arg, another_arg)
end
end
And use it like this:
rake database:reset_and_create

Rails's Rake task takes exceptionally long to execute? [duplicate]

rake --tasks takes about 18s to run. This is just the time it takes to load all the tasks, as a result any task I define will take at least this amount of time to run :
$time rake --tasks
rake db:clean # Cleaning up database
rake passenger:restart # Restart Application
rake spec # Run specs
real 0m18.816s
user 0m7.306s
sys 0m5.665s
My Rakefile :
$: << "."
require "rubygems"
require "rspec/core/rake_task"
desc "Run those specs"
task :spec do
RSpec::Core::RakeTask.new(:spec) do |t|
t.rspec_opts = %w{--colour --format progress}
t.pattern = 'spec/*_spec.rb'
end
end
task :default => :spec
Any idea why rake takes to much times ?
Thanks
Try spring
Command line will look like:
spring rake -T
It will take more time running the first time, but subsequent runs will be very fast.
This solution worked for me: Faster rake tasks in Rails.
I had to do a little variation where I created a lib/tasks/no_rails directory and put all the Rake files which do not need Rails in there and loaded only those using the above method.
I like the solution Pratik mentions for the general case of loading rails for tasks that need it and not for those that don't, for any rake task without having to remember beforehand.
A less-invasive method to run a rake task that doesn't need rails is to use the -f rake option to tell rake to use a particular Rakefile. This way, rake won't go looking for rake tasks in all of rails.
For example, assuming your task above is in a file called Rakefile at the top level of your project and your Rakefile doesn't do anything that loads Rails like require File.expand_path('../config/application', __FILE__), you can do:
$ rake -f Rakefile spec
and it should run your spec task much faster. Try $ time rake -f Rakefile -T; I did this with a rails-independent Rakefile of mine and got:
real 0m1.543s
user 0m1.308s
sys 0m0.201s
The downside is you have to remember to specify this option every time, and not to specify it if you want to run a rake task from rails like rake db:migrate.
The entire rails environment has to be loaded, therefore even simple rake tasks such as rake --tasks take a while. Opening a console with rails console or script/console takes a similar time. You may try to hack Ruby or Rails to speed up rake, but too much optimization can be bad if you want to switch to a newer version later. Since the rails environment must be loaded, cleaning up routes may also help.

How do I run a ruby script, that I put in my /lib/tasks/ directory in my Rails app, once?

Eventually I would like to get to setting it up as a Rake task and do a cron job, but for right now...all I want to do is take my ruby script that used to work as a standalone script and have it work within my Rails app.
I renamed the file to be .rake instead of .rb and tried doing rake my_script at the command-line, but that gave me this error message:
rake aborted!
Don't know how to build task 'my_script'
(See full trace by running task with --trace)
How do I run this script within my Rails environment?
This is the first time I am doing something like this, so any assistance would be greatly appreciated.
Thanks.
I think what you're looking for is rails runner. I know in Rails 2.3.x you'd do
ruby script/runner <your file>
In Rails 3 it might be slightly different.
http://guides.rubyonrails.org/command_line.html#rails-runner
The primary difference between a runner and a rake task is : runner would boot rails while rake task doesn't (you can tell it to do so).
Since rake can do both (boot/no boot), there's no concept of runner in rails-3 anymore.
So, create a rake task: whatever_name.rake
Example:
desc "This task does awesome stuff"
task :do_awesome_stuff do
awesome_method
end
def awesome_method
#put your ruby code here
end
Now from your command prompt, type rake do_awesome_stuff to execute this rake task.
To make it boot Rails, change task definition to this:
task :do_awesome_stuff => :environment do

Resources