Mix-in の中で before :save を仕掛ける
Mix-in を include しても before :save などに、 Hook を仕掛けることができない。
before は module が定義される時に通常の method として実行されるが、そのモジュールには :save というメソッドは存在しないためである。
module が対象の model に include された後に、対象の model の instance 上で before :save を実行する必要がある。次のように記述すると、これを実現できる。
module TargetModule def self.included(base) base.before :save do : : end end end
これで、 include しただけで Hook の設定が行われる。
以上は、 dm-optlock module のソースコードを読んでいて気がついた。
self.included 自体は ruby の機能の一つだ。