JT's Blog

Do the right things and do the things right.

Ruby Forwardable (Delegator)

| Comments

ruby method 是一行程式碼且執行動作跟 method_name 相同,就可以使用 forwardable 簡化

語法

1
2
3
4
5
6
7
8
9
10
11
12
13
# Define method as delegator instance method with an optional alias name ali.
# Method calls to ali will be delegated to accessor.method.
def_instance_delegator(accessor, method, ali = method)

# Shortcut for defining multiple delegator methods,
# but with no provision for using a different name.
def_instance_delegators(accessor, *methods)

# 定義單一個 method, alias for: def_instance_delegator
def_delegator(accessor, method, ali = method)

# 定義多個 methods, alias for: def_instance_delegators
def_delegators(accessor, *methods)

範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 一般 class Queue
class Queue
  def initialize
    @q = []
  end

  def push(val)
    @q.push(val)
  end
  def shift
    @q.shift
  end
  def size
    @q.size
  end
end

# 使用forwardable 可以把method 優化
require 'forwardable'

class Queue
  extend Forwardable
  def initialize
    @q = []
  end

  def_delegator :@q, :push
  def_delegator :@q, :shift
  def_delegator :@q, :size
end

# 更可以一次宣告多個
class Queue
  extend Forwardable
  def initialize
    @q = []
  end

  def_delegators :@q, :push, :shift, :size
end

Reference

Comments