Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails share code between migrations (aka concerns)

I have a few migrations within identical helpers

  private

  def add_earthdistance_index table_name, options = {}
    execute "CREATE INDEX %s_earthdistance_ix ON %s USING gist (ll_to_earth(%s, %s));" %
      [table_name, table_name, 'latitude', 'longitude']
  end

  def remove_earthdistance_index table_name
    execute "DROP INDEX %s_earthdistance_ix;" % [table_name]
  end

And I'm trying to avoid copy-paste them every time. Is there any way to share code between migrations without monkey-patching the base class? I want to find something like concerns for models.

like image 946
Arsen Avatar asked Jan 06 '23 19:01

Arsen


1 Answers

Solution

Add config.autoload_paths += Dir["#{config.root}/db/migrate/concerns/**/"] to config/application.rb

Create db/migrate/concerns/earthdistanceable.rb file within

module Earthdistanceable
  extend ActiveSupport::Concern

  def add_earthdistance_index table_name, options = {}
    execute "CREATE INDEX %s_earthdistance_ix ON %s USING gist (ll_to_earth(%s, %s));" %
      [table_name, table_name, 'latitude', 'longitude']
  end

  def remove_earthdistance_index table_name
    execute "DROP INDEX %s_earthdistance_ix;" % [table_name]
  end

end

Use it:

class CreateRequests < ActiveRecord::Migration[5.0]
  include Earthdistanceable

  def up
    ...
    add_earthdistance_index :requests
  end

  def down
    remove_earthdistance_index :requests

    drop_table :requests
  end

end
like image 64
Arsen Avatar answered Jan 14 '23 12:01

Arsen