ruby Rails在迁移之间共享代码(又称关注点)

sdnqo3pr  于 2023-01-16  发布在  Ruby
关注(0)|答案(2)|浏览(127)

我在相同的helper中进行了一些迁移

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

我尽量避免每次都复制粘贴它们。有没有办法在迁移之间共享代码,而不用猴子修补基类?我想为模型找到类似concerns的东西。

fzsnzjdm

fzsnzjdm1#

    • 解决方案**

config.autoload_paths += Dir["#{config.root}/db/migrate/concerns/**/"]加到config/application.rb
在以下位置创建db/migrate/concerns/earthdistanceable.rb文件

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

使用它:

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
huus2vyu

huus2vyu2#

我认为你可以这样做:

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

迁移

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

相关问题