I need to reuse the same method across many migrations. My goal is to avoid code duplication. I tried to do it as shown below, by putting the shared method into file lib/migration_helper.rb
and using include MigrationHelper
in the migrations that use the shared method.
Is there a more standard way of sharing code in different migrations?
In particular, I put the helper file into lib
directory - is this the correct place?
## lib/migration_helper.rb
# Methods shared across migrations.
module MigrationHelper
def my_shared_method
# some shared code
end
end
## db/migrate/do_something.rb
class DoSomething < ActiveRecord::Migration[5.2]
include MigrationHelper
# rubocop:disable Metrics/MethodLength
def up
# some code
my_shared_method
end
# rubocop:enable Metrics/MethodLength
def down
# more code
my_shared_method
end
SEE ALSO:
I got a few ideas from these questions, but they do not fully answer my question:
Custom helper methods for Rails 3.2 Migrations
Rails share code between migrations (aka concerns)
Accessing custom helper methods in rails 3 migrations
This repo has examples of a much more complex version of what I want, with a whole hierarchy of helpers. I need a simpler solution:
https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/database/migration_helpers.rb
https://gitlab.com/gitlab-org/gitlab-foss/-/blob/master/db/migrate/20220808133824_add_timestamps_to_project_statistics.rb