Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
859 views
in Technique[技术] by (71.8m points)

ruby on rails - How do I override rake tasks for a custom database adapter?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...