Skip to content

Instantly share code, notes, and snippets.

@r7kamura
Last active December 10, 2015 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save r7kamura/4374756 to your computer and use it in GitHub Desktop.
Save r7kamura/4374756 to your computer and use it in GitHub Desktop.
about Forwardable module of Ruby

Forwardable

メソッドの委譲を実現する。 例えば内部的に配列を持ちながらCollectionを表現するクラスを作る場合、eachを配列に委譲すると便利。

require "forwardable"
class Collection
  extend Forwardable
  include Enumerable

  delegate_defs :@list, :each, :size

  def initialize(list)
    @list = list
  end
end

Module#delegate

ActiveSupportにもdelegateを支援する機能がある。 これは内部実装的には宣言した瞬間にメソッドを定義するというやつなのだけど、便利なのでよく使う。 上記のForwardableの例はModule#delegateを利用して下記のように記述できる。

require "active_support/core_ext/module/delegation"
class Collection
  extend Forwardable
  include Enumerable

  delegate :each, :size, :to => :@list

  def initialize(list)
    @list = list
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment