Skip to content

Commit

Permalink
Register database tasks properly
Browse files Browse the repository at this point in the history
Also use class for Rails < 5.2 and class name for Rails >= 5.2 to match
AR's behavior

Fix #151
  • Loading branch information
tagliala committed Jun 15, 2023
1 parent 8a08cae commit b75df79
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
2 changes: 1 addition & 1 deletion lib/chrono_model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def self.history_models
end
end

if defined?(Rails)
if defined?(Rails::Railtie)
require 'chrono_model/railtie'
end

Expand Down
28 changes: 16 additions & 12 deletions lib/chrono_model/railtie.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# frozen_string_literal: true

require 'active_record/tasks/chronomodel_database_tasks'

module ChronoModel
class Railtie < ::Rails::Railtie
TASKS_CLASS = ActiveRecord::Tasks::ChronomodelDatabaseTasks

def task_config
if Rails.version < '6.1'
Expand All @@ -10,17 +14,18 @@ def task_config
end
end

# Register our database tasks under our adapter name
if Rails.version < '5.2'
ActiveRecord::Tasks::DatabaseTasks.register_task(/chronomodel/, TASKS_CLASS)
else
ActiveRecord::Tasks::DatabaseTasks.register_task(/chronomodel/, TASKS_CLASS.to_s)
end

rake_tasks do
if Rails.application.config.active_record.schema_format != :sql
raise 'In order to use ChronoModel, config.active_record.schema_format must be :sql!'
end

tasks_class = ActiveRecord::Tasks::ChronomodelDatabaseTasks

# Register our database tasks under our adapter name
#
ActiveRecord::Tasks::DatabaseTasks.register_task(/chronomodel/, tasks_class)

if Rails.version < '6.1'
# Make schema:dump and schema:load invoke structure:dump and structure:load
Rake::Task['db:schema:dump'].clear.enhance(['environment']) do
Expand All @@ -32,19 +37,18 @@ def task_config
end
end

desc "Dumps database into db/data.NOW.sql or file specified via DUMP="
desc 'Dumps database into db/data.NOW.sql or file specified via DUMP='
task 'db:data:dump' => :environment do
target = ENV['DUMP'] || Rails.root.join('db', "data.#{Time.now.to_f}.sql")
tasks_class.new(task_config).data_dump(target)
TASKS_CLASS.new(task_config).data_dump(target)
end

desc "Loads database dump from file specified via DUMP="
desc 'Loads database dump from file specified via DUMP='
task 'db:data:load' => :environment do
source = ENV['DUMP'].presence or
raise ArgumentError, "Invoke as rake db:data:load DUMP=/path/to/data.sql"
tasks_class.new(task_config).data_load(source)
raise ArgumentError, 'Invoke as rake db:data:load DUMP=/path/to/data.sql'
TASKS_CLASS.new(task_config).data_load(source)
end
end

end
end

0 comments on commit b75df79

Please sign in to comment.