Defining an existing rake task again appends to the original, but I'd like to prepend to the db:migrate task. I want to raise an error beforehand in some cases. Is there a good way to prepend to an existing rake task?
Try adding a db:custom task on 'db' namespace and invoke db:migrate with enhance method
# add your custom code on db:custom
namespace 'db' do
task 'custom' do
puts "do custom db stuff"
end
end
# invoke db:migrate
Rake::Task['db:migrate'].enhance [:custom]
Might be better to define your own task and call db:migrate inside.
namespace :custom_db do
desc 'migrate db if condition true'
task :migrate do
if true #your condition
Rake::Task['db:migrate'].invoke
else
#process errors
end
end
end
Related
In my lib/tasks folder I added a new .rake file.
In the rake task, I am doing this:
p = Post.new( ....)
p.save!
When I run my task, I get the error:
rake aborted!
uninitialized constant Post
What do I have to do to import my Post model?
I'm thinking you're probably missing the environment declaration. This is necessary in order for Rake to know about your Rails environment. Your rake task call should look something like this:
task :my_rake_task => [:environment] do
# Your code here
end
Let me know if that solves the problem!
You want to make the task dependent on the rails environment. You can do so by specifying the => :environment after the task declaration as such:
namespace :my_task do
desc "an example task"
task :create_post => :environment do
Post.new .... # the rest of the implementation
end
end
I have a Rails 2.2 project in which I want to override the functionality of the rake db:test:prepare task. I thought this would work, but it doesn't:
#lib/tasks/db.rake
namespace :db do
namespace :test do
desc "Overridden version of rails' standard db:test:prepare task since the schema dump used in that can't handle DB enums"
task :prepare => [:environment] do
puts "doing db:structure:dump"
Rake::Task['db:structure:dump'].invoke
puts "doing db:test:clone_structure"
Rake::Task['db:test:clone_structure'].invoke
end
end
end
I get the standard task's behaviour. If I change the name of the task to :prepare2 and then do rake db:test:prepare2, then it works fine. The natural conclusion I draw from this is that my rake tasks are being defined before the built-in Rails ones, so mine is overridden by the standard :prepare task.
Can anyone see how I can fix this? I'd rather override it than have to use a new task. Thanks, max
If you define a rake task that already exists, its execution gets appended to the original task's execution; both tasks will be executed.
If you want to redefine a task you need to clear the original task first:
Rake::Task["db:test:prepare"].clear
It's also useful to note that once a task has been executed in rake, it won't execute again even if you call it again. This is by design but you can call .reset on a task to allow it to be run again.
You have to remove the default task before adding your own:
Rake.application.instance_variable_get('#tasks').delete('db:test:prepare')
namespace 'db' do
namespace 'test' do
task 'prepare' do
# ...
end
end
end
A fairly popular idiom is to create a convenience method called remove_task like so:
Rake::TaskManager.class_eval do
def remove_task(task_name)
#tasks.delete(task_name.to_s)
end
end
def remove_task(task_name)
Rake.application.remove_task(task_name)
end
(Source: drnic/newgem)
Create a new project.rake file at lib/tasks/, and paster below code into it.
namespace :mv do
desc "Display hint and info for your rails 4 project"
task info: :environment do
puts 'Run rake test to test'
end
end
task(:default).clear.enhance ['mv:info']
inspired by Krasimir Angelov's blog
To prepare database for my Ruby on Rails 3 application I need to run the following steps in the Terminal:
rake db:create
rake db:migrate
rake db:seed
Is it possible to do all those steps in one? Maybe it is possible running a 'rake' command that will "fire" another 'rake' command... but how?!
You can define your own rake tasks which call other tasks as prerequisites:
# lib/tasks/my_tasks.rake
namespace :db do
desc "create, migrate and seed"
task :do_all => [:create,:migrate,:seed] do
end
end
Normally the body of the task would contain Ruby code to do something, but in this case we are just invoking the three prerequisite tasks in turn (db:create,db:migrate,db:seed).
The empty do-end blocks are not needed, e.g. (for zetetic's answer)
$ cat lib/tasks/my_tasks.rake
# lib/tasks/my_tasks.rake
namespace :db do
desc "create, migrate and seed"
task :do_all => [:create,:migrate,:seed]
end
rake db:create db:migrate db:seed will do all that.
zeteitic got it right, but in the event you don't want to namespace this task under "db", you'd want something more like this:
desc "Bootstrap database."
task :bootstrap => ["db:create", "db:migrate", "db:seed"] do; end
And on the command line:
rake bootstrap
# => create, migrate and seed db
I have a Rake task that loads configuration data into the DB from a file, is there a correct ruby/rails way to call it on a migration up?
My objective is to sync my team DB configs, without have to broadcast then to run the task lalala
def self.up
change_table :fis_situacao_fiscal do |t|
t.remove :mostrar_endereco
t.rename :serie, :modelo
end
Faturamento::Cfop.destroy_all()
#perform rake here !
end
UPDATE
How I do now, and works:
system('rake sistema:load_data file=faturamento/cfop')
And this is the suggestion from #Ryan Bigg, and it's exception:
Rake::Task['rake sistema:load_data file=faturamento/cfop'].invoke()
.
== AlterSituacaoFiscalModeloEndereco: migrating ====================
-- change_table(:fis_situacao_fiscal)
-> 0.0014s
rake aborted!
An error has occurred, this and all later migrations canceled:
Don't know how to build task 'rake sistema:load_data file=faturamento/cfop'
Where it went wrong?
Yes there's a way to do that:
Rake::Task['your_task'].invoke
Update
Do not put rake inside the brackets, just the name of the task. You should set an ENV variable when running this:
In the console
FILE=somefile.text rake db:sistema:load_data
Calling it separately
FILE=somefile.text rake some:other:task:that:calls:it
This will be available in your tasks as ENV['file']
Note that if you call the Rake task with 'system', you need to check the process status afterwards and raise an exception if the Rake task failed. Otherwise the migration will succeed even if the Rake task fails.
You can check the process status like this:
if !($?.success?)
raise "Rake task failed"
end
Invoking the rake task is a nicer option - it will cause the migration to fail if the Rake task fails.
You can execute a rake task from within a loaded Rails environment with either Rake::Task['namespace:task'].invoke or Rake::Task['namespace:task'].execute.
You can pass data to the task inside of the invoke or execute method. Example:
Rake::Task['namespace:task'].invoke(paramValue)
This param can be handled in the rake task as follows:
namespace :namespace do
desc "Example description."
task :task, [:param] => :environment do |t, args|
puts args[:param]
...
end
end
This can be executed on the console as:
bundle exec rake namespace:task[paramValue]
More info: https://medium.com/#sampatbadhe/rake-task-invoke-or-execute-419cd689c3bd
This decision fits better, IMHO.
In your case it would be smth like this:
backup_env = ENV.slice('file') if ENV.key?('file')
ENV['file'] = 'faturamento/cfop'
Rake::Task['sistema:load_data'].invoke
ENV.delete 'file'
ENV.merge!(backup_env) if backup_env
Every time I want to run Rake test the task db:test:prepare is being called and it rebuilds my test environment database from schema.rb and migrations. What I would like to achive is to disable the call of db:test:prepare when I want to test make Rails application. Is it possible without modifying Rails gem?
Here's a solution I've seen around:
In your Rakefile:
Rake::TaskManager.class_eval do
def remove_task(task_name)
#tasks.delete(task_name.to_s)
end
end
In lib/tasks/db/test.rake:
Rake.application.remove_task 'db:test:prepare'
namespace :db do
namespace :test do
task :prepare do |t|
# rewrite the task to not do anything you don't want
end
end
end
There is a plugin that takes care of this for you: override_rake_task. Here is a quick usage example:
namespace :db do
namespace :test do
override_task :prepare do; end
end
end
For some older version of rails - you can place Rake::Task['db:test:prepare'].clear at the end of your Rakefile