Rails share code between migrations (aka concerns)
Asked Answered
P

2

5

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.

Partlow answered 3/7, 2016 at 19:40 Comment(0)
P
8

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
Partlow answered 3/7, 2016 at 20:23 Comment(0)
I
4

I think you could do something like:

# lib/helper.rb
module Helper
  def always_used_on_migrations
    'this helps' 
  end
end

Migration

include Helper
class DoStuff < ActiveRecord::Migration
  def self.up
    p always_used_on_migrations
  end

  def self.down
    p always_used_on_migrations
  end
end
Isoprene answered 3/7, 2016 at 19:50 Comment(4)
Nice. But too explicit for me. I'd like to find something like concerns for models.Partlow
Oh okay, sorry if it didn't suit you.Isoprene
@Arsen: do you know how concerns work? It's just a module that you include in a class. And a migration is just a class. It's the same thing as with models, literally.Trygve
@SergioTulentsev I know now. Because I have just implemented it.Partlow

© 2022 - 2024 — McMap. All rights reserved.