Alex's Slip-box

These are my org-mode notes in sort of Zettelkasten style

Rake Tasks

:ID: 6CCD57E5-23C9-4765-9016-3DECCADEF1D7

Just some notes on using rake (Ruby Make) tasks.

See also https://ruby.github.io/rake/

And https://graceful.dev/courses/the-freebies/modules/rake-and-project-automation/topic/episode-131-rake-rules/

# Testing Rake Tasks

This is one approach to testing a rake task. Another might be to encapsulate the task in a module and test that. That wouldn’t quite be a complete, but it might be enough is some cases.

require "rake"

RSpec.describe 'projects:todos' do
  before do
    load File.expand_path('../../../../lib/tasks/projects/todos.rake', __FILE__)
    Rake::Task.define_task :environment
  end

  subject do
    Rake::Task['projects:todos']
  end

  it 'puts projects to stdout' do
    expect { subject.execute }.to output(
                                    "Project One"
                                    "- [X] Todo Item 1"
                                    "- [ ] Todo Item 2"
                                    "- [ ] Todo Item 3"
                                    ""
                                    "Project Two"
                                    "- [ ] Todo Item 1"
                                  ).to_stdout
  end
end

# Rails

# Generate a rake task in rails

$ rails g task_namespace task_one task_two

will produce lib/tasks/task_namespace.rake:

namespace :task_namespace do
  desc "TODO"
  task task_one: :environment do
  end

  desc "TODO"
  task task_two: :environment do
  end
end

# What is environment?

In this example, the task depends on the environment task. For rails, I think this loads the environment as specified in config/environment.rb

# List all available rake tasks

$ rake -T

# Some tips

  • Write a good description
  • Namespace task related tasks
  • Use folder structure to group related tasks (ie, one task per file)
  • Extract task logic to modules
  • Provide useful output to stdout like start, progress and results
  • Write logs

# Shell Commands in Rake

# Ignore errors from shelled out commands

Force a 0 exit code

sh "the command || true"

or pass an empty block

sh "your shell command" do |ok,res|
end

# Passing Args to Rake Task

namespace :foo do
  desc 'Seed flag rules with several conditions each'
  task :bar, %i[arg1 arg2] => :environment do |_t, args|
    arg1 = args[:arg1]
    arg2 = args[:arg2]
    # . . .
  end
end
rake foo:bar[arg1,arg2]

When using zsh, the brackets need to be escaped. Prefix the above command with noglob.

# Invoking Rake Tasks in the Console

require 'rake'
Rails.application.load_tasks
Rake::Task['my_task'].invoke

Search Results