Featured image

Rake is one of the best tools created in Ruby and widely used for running scripts. In my opinion, its beautiful DSL inspired the creation of other projects, like Capistrano.

While Rake is mostly used for running build scripts, code checks, and tests, I believe it can also be used to some extent for running business tasks related to your project.

But there is one thing to keep in mind when writing your scripts: avoid exceeding 10-15 lines of code inside a task block. If your logic doesn’t fit within this limit, you can create a separate class to be used inside the task. Just make sure to place this class inside a namespace, because once loaded by the interpreter, it becomes globally available.

Do you use Rake tasks to run business logic in your projects? For what other purposes have you used Rake?

# frozen_string_literal: true

# Example of execution: rake hello

task :hello do
  puts 'Hello, Ruby'
end

task :heavy_action do
  RakeTask::HeavyAction.new.call
end

module RakeTask
  class HeavyAction
    def initialize
      # ...
    end

    def call
      puts 'download file'
      puts 'check file'
      puts 'load data to db'
      puts 'send notification'
      puts 'other cleanup actions'
    end
  end
end