1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

親クラスも含めて、メソッドの定義場所を特定する

Posted at

経緯

このモンキーパッチを解読していたところ、元のcolumnsがどのクラスで定義されているかを知りたくなった。

module ActiveRecordInvisibleColumn
  INVISIBLE_COLUMNS = {
    'foos' => ['bar'],
  }.freeze
  def columns(table_name)
    super.delete_if { |column| INVISIBLE_COLUMNS.fetch(table_name, []).include?(column.name) }
  end
end

ActiveSupport.on_load :active_record do
  ActiveRecord::ConnectionAdapters::Mysql2Adapter.prepend(ActiveRecordInvisibleColumn)
end

ハマった罠

initializeに引数が必要らしく、面倒。

irb(main):036:0> ActiveRecord::ConnectionAdapters::Mysql2Adapter.new
ArgumentError: wrong number of arguments (given 0, expected 4)

irb(main):037:0> ActiveRecord::ConnectionAdapters::Mysql2Adapter.new(nil, nil, nil, nil)
NoMethodError: undefined method `fetch' for nil:NilClass

結論

これで解決した。
allocateはinitializeをskipしてインスタンス化できるメソッド。

irb(main):035:0> ActiveRecord::ConnectionAdapters::Mysql2Adapter.allocate.method(:columns).source_location
=> ["/Users/xxxx/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-4.2.11.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb", 469]

参考

https://qiita.com/jnchito/items/fc8a61b421d026a23ffe
https://techracho.bpsinc.jp/hachi8833/2019_07_04/75432
https://eagletmt.hateblo.jp/entry/2017/09/24/004709

共同編集者

@popmac

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?