How do I override rake tasks for a custom database adapter?

我只是一个虾纸丫 提交于 2019-11-28 01:01:12

问题


I've written a custom database adapter that works correctly and effectively when a rails server is running. I would now like to add the usual rake task definitions for creating, dropping and migrating the database.

I would like to implement:

db:[drop|create|migrate]

How do I package these definitions with my gem so that they override the default ones for anyone who uses the gem?

I looked through the source of other adapters but all the rake task logic appears to be baked into active_record itself, each task just switches on the adapter name.


回答1:


This is possible with:

# somewhere in your gem's tasks
Rake::Task['db:create'].clear

# then re-define
namespace 'db' do
  task 'create' do
    # ...
  end
end

When Take::Task#[] can't resolve a task it will fail. If your tasks sometimes exists, you might want to:

task_exists = Rake.application.tasks.any? { |t| t.name == 'db:create' }
Rake::Task['db:create'].clear if task_exists

If you want to add tasks to an existing rake task, use enhance.

Rake::Task['db:create'].enhance do
  Rake::Task['db:after_create'].invoke
end



回答2:


You can write

Rake::Task['db:create'].clear

to delete the original task before redefining it. Also check out Overriding rails' default rake tasks



来源:https://stackoverflow.com/questions/6205968/how-do-i-override-rake-tasks-for-a-custom-database-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!