Saturday, October 1, 2022
HomeRuby On RailsAutomate Rake Duties | Drifting Ruby

Automate Rake Duties | Drifting Ruby


# Terminal
bin/rails g mannequin launch job
bin/rails g job launch execute
bin/rails g job hi there world
bin/rails g job firm one thing

# Only a neat instance of executing code from the shell
bin/rails runner "Launch.all.destroy_all"

# Add in your deployment scripts
bin/rails launch:execute
# lib/duties/launch.rake
require 'task_runner'

namespace :launch do
  desc "Rake duties execute every launch"
  job execute: :setting do
    TaskRunner.execute("hi there:world", force_run: true)
    TaskRunner.execute("firm:one thing")
    TaskRunner.execute("firm:dangerous")
    TaskRunner.execute("firm:one thing")
  finish
finish
# lib/duties/task_runner.rb
class TaskRunner
  def self.execute(job, force_run: false)
    new(job, force_run).execute
  finish

  def initialize(job, force_run)
    @job = job
    @force_run = force_run
  finish

  def execute
    places "nn"
    return if already_executed?

    places inexperienced("#{@job} execute began.")
    start_timer
    Rake::Job[@task].invoke
    stop_timer
    places inexperienced("#{@job} completed in #{elapsed_time} seconds.")

    record_task_record
  rescue StandardError => e
    places pink("#{@job} failed. Error: #{e.message}")
  finish

  personal

  def already_executed?
    return false if @force_run == true

    executed = Launch.find_by(job: @job).current?
    places yellow("#{@job} already executed.") if executed
    executed
  finish

  def start_timer
    @start_timer ||= Time.now.to_f
  finish

  def stop_timer
    @stop_timer ||= Time.now.to_f
  finish

  def elapsed_time
    '%.2f' % (stop_timer - start_timer)
  finish

  def record_task_record
    return if @force_run == true
    Launch.create(job: @job)
  finish

  def pink(string); "e[31m#{string}e[0m"; end
  def green(string); "e[32m#{string}e[0m"; end
  def yellow(string); "e[33m#{string}e[0m"; end
end
# lib/tasks/hello.rake
namespace :hello do
  desc "Say hello"
  task world: :environment do
    puts "Hello World!"
    sleep 0.5
  end
end
# lib/tasks/company.rake
namespace :company do
  desc "change records or something"
  task something: :environment do
    puts "this is the company something rake task"
    puts "this rake task (company:something) is being executed"
  end

  desc "bad code"
  task bad: :environment do
    puts "bad code"
    raise "this is an error"
  end
end
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments