LoginSignup
3
1

More than 3 years have passed since last update.

Ruby のクラスメソッドを委譲したい時は SingleForwardable を使おう

Posted at

Ruby 2.7.0 リファレンスマニュアル > ライブラリ一覧 > forwardableライブラリ > SingleForwardableモジュール より。

結論

クラスメソッドの委譲には SingleForwardable が使える(というのが調べてもパッと出てこなかったのでメモ :pencil:)。

require 'forwardable'

class Implementation
  def self.service
    puts "serviced!"
  end
end

module Facade
  extend SingleForwardable
  def_delegator :Implementation, :service
end

Facade.service # => serviced!

具体例

例えば、Bugsnag gem を使いたいが、そのまま直で使うと後で Sentry に乗り換えづらいので、BugReport モジュールを用意してきちんとラップしておこうと思った場合などに、クラスメソッドの委譲が行きます。

Bugsnagの例
module BugReport
  extend SingleForwardable
  def_delegator :Bugsnag, :notify
end

BugReport.notify # Bugsnag.notify が実行される

Rails 使ってる場合は ActiveSupportdelegate 使っても良いと思います。

delegateの例
module BugReport
  class << self
    delegate :notify, to: :Bugsnag
  end
end

BugReport.notify # Bugsnag.notify が実行される

委譲、便利ですね :thumbsup:

3
1
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
3
1