Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to include a module in rake tasks without polluting the global scope?

I wonder — is it possible to create private helpers for rake tasks, no matter how I try to do it they end up being available in the in the global scope and also are available as methods of any object. For example:

## this is what I need

module MyRakeHelpers
  def helper_1
  end

  def helper_2
  end
end

include RakeHelpers

task :sometask do
  helper_1
  helper_2
end

## And this should not work:

# global scope
helper_1

"a random object".helper_1

class RandomClass
  def foo
    helper_1
  end
end
like image 258
Dmitry Sokurenko Avatar asked Mar 11 '23 22:03

Dmitry Sokurenko


1 Answers

Here's what worked for me:

module MyRakeHelpers
  def helper
    puts 'foo'
  end
end

module MyRakeTasks
  extend Rake::DSL
  extend MyRakeHelpers

  task :some_task do
    helper
  end
end

In short, you can use the Rake DSL in a different scope by including (or extending) Rake::DSL. From the source:

DSL is a module that provides #task, #desc, #namespace, etc. Use this when you'd like to use rake outside the top level scope. For a Rakefile you run from the command line this module is automatically included.

task uses Rake::Task#define_task under the hood, which you could also use to write your own DSL.

Thanks to How To Build Custom Rake Tasks; The Right Way for the tip about define_task.

like image 61
Max Wallace Avatar answered Apr 08 '23 09:04

Max Wallace