diary

I like Hatena Star with a text selection.

2020-08-17

github.com

active_decorator のキーワード引数警告を直した。

これは結構むずかしかった。 以前に社内で**kwargsを使うパッチを他の人に書いてもらっていたのだけど、これはPRのdescriptionにあるとおり、Ruby 2.7では動くもののRuby 2.6では動かなかった。

この原因を追ってみると、どうやらRuby 2.7でsendの挙動が変わったみたい。

def m(*args)
  p args
end

args = []
kwargs = {}
send :m, *args, **kwargs
# with 2.6 => [{}]
# with 2.7 => []

これは(public_sendだけど)bugsにもチケットがあるし、ruby2_keywordsはこのために導入されたとjeremyevans氏も言っているので、意図された変更でありruby2_keywordsを使うべき局面っぽい。 https://bugs.ruby-lang.org/issues/16421

なのでruby2_keywordsを使って修正した。


TIL: IO#reopen すると self のクラスが変わる。

io = IO.popen('ls')
p io.class # => IO
f = File.open('/etc/hosts')
p f.class # => File
io.reopen(f)
p io.class # => File

https://docs.ruby-lang.org/ja/latest/method/IO/i/reopen.html るりまにも書いてあった。

class ClassChangable < IO
  FD = IO.sysopen('/dev/null')

  def initialize
    super FD
  end

  def change_class_to(klass)
    raise TypeError, "class must inherit ClassChangable" unless klass < ClassChangable
    reopen klass.new
  end
end

class A < ClassChangable
end
class B < ClassChangable
end

a = A.new
b = B.new
p a.class # => A
p b.class # => B

a.change_class_to B
p a.class # => B

応用例。