Mike
Mike

Reputation: 19727

Can mixins be used to reduce redundancy in Rake files?

I have a Rakefile with 5 different namespaces, each with the same 6 method signatures. The bodies of each signature are exactly the same. They differ only in the values of the instance variables that the methods use.

A concrete example:

namespace :db do
  namespace :foo do
    @user = "foo"
    task :create do
      function_call_to_do_stuff @user
    end
  end

  namespace :bar do
    @user = "bar"
    task :create do
      function_call_to_do_stuff @user
    end
  end
end

Ideally, I'd like to be able to do something like this:

module Migratable
  task :create do
    function_call_to_do_stuff @user
  end
end

namespace :db do
  namespace :foo do
    include Migratable
    @user = "foo"
  end

  namespace :bar do
    include Migratable
    @user = "bar"
  end
end

When I do what is shown above, the tasks in the mixin don't register as tasks for the appropriate namespaces - or as tasks at all for that matter. Is there a way to accomplish this?

Upvotes: 1

Views: 284

Answers (1)

joelparkerhenderson
joelparkerhenderson

Reputation: 35483

Rake is just Ruby, so you can use modules with include and extend as you like.

That said, there's an easier way to accomplish what you want: make your modules just plain Ruby.

Example:

# migratable.rb
module Migratable
  def create x
    puts x
  end
end


# rakefile.rb
require_relative 'migratable'
include Migratable

namespace :db do

  task :foo do
    @user = "foo"
    create(@user)
  end

  task :bar do
    @user = "bar"
    create(@user)
  end

end

In Rake you should set instance variables that may be overwritten within tasks, not within namespaces. This is because namespaces are all parsed before the task runs.

Upvotes: 1

Related Questions