経緯
このモンキーパッチを解読していたところ、元の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