Skip to content

Instantly share code, notes, and snippets.

@gomo
Last active December 4, 2018 01:35
Show Gist options
  • Save gomo/17fc8bc2825f4a4ae9f02c2f8fec5efa to your computer and use it in GitHub Desktop.
Save gomo/17fc8bc2825f4a4ae9f02c2f8fec5efa to your computer and use it in GitHub Desktop.
helper methods and before/after hook for rails task using class inherit
# frozen_string_literal: true
# lib/tasks/data.rb
require 'tasks'
module Tasks
class Data
include ::Tasks
before_execute do
Rake::Task[:environment].invoke
ActiveRecord::Base.logger = Logger.new(STDOUT)
end
after_execute do
Rails.cache.clear
end
# helper methods for Tasks::Data are here.
end
end
# frozen_string_literal: true
# lib/tasks/data/sometask.rake
require 'tasks/data'
namespace :data do
desc 'Some data task'
task :add_map, [:site] do |task, args|
Tasks::Data.new(task, args).execute do
# Implement task here.
end
end
end
# frozen_string_literal: true
# lib/tasks.rb
module Tasks
extend ActiveSupport::Concern
extend ActiveModel::Callbacks
included do
define_callbacks :execute
end
attr_reader :task, :args
def initialize(task, args)
@task = task
@args = args
end
def execute(&block)
run_callbacks :execute do
instance_exec(&block)
end
end
# helper methods for all tasks are here.
class_methods do
def before_execute(*names, &block)
names.each do |name|
set_callback(:execute, :before, name)
end
set_callback(:execute, :before, &block) if block_given?
end
def after_execute(*names, &block)
names.each do |name|
set_callback(:execute, :after, name)
end
set_callback(:execute, :after, &block) if block_given?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment