JT's Blog

Do the right things and do the things right.

Ruby Module - Namespace | Mixin | Include | Extend

| Comments

module 算是Ruby 的獨有特色,瞭解後在程式開發或是閱讀原始碼有很大的幫助

宣告

示範module 內是可以包含多種內容,但實際在設計時,還是依照功能分類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Module name 第一個字必需大寫
module Module_name
  # adding class
  class MyClass
  end

  # adding method
  def myMethod
  end

  # namespace
  module another_moudle_name
  end
end

用途

  • NameSpace
  • Mixin

NameSpace

用來區分命名空間,當有相同命名時,可透過module 區分命名空間

Mixin

因為Ruby Class有單一繼承的限制。所以就可透過此方法,擴充Class 的功能

Mixin 分成兩類:

  1. include:class instance 才能操作

  2. extend:不需instance 就可以透過 class_name.method_name 操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module Power
  def calPower(num)
    num ** num
  end
end

module StringUtil
  def repeating(num, string)
    string * num
  end
end

class Example
  include Power
  extend StringUtil
end

p Example.new.calPower(2) # 4
p Example.repeating(2,"a") # "aa"

單獨操作Module

以上介紹都是把module 放在class 內,再透過mixin 方式操作,但如果想要直接操作可以根據以下方式:

  • module_function
  • self.method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module CompanyA
  def greeting(name)
    "Hello #{name} at CompanyA"
  end

  module_function :greeting
end

# 上下功能相同
module CompanyB
  def self.greeting(name)
    "Hello #{name} at CompanyB"
  end
end

p CompanyA.greeting("JT") # "Hello JT at CompanyA"
p CompanyB.greeting("JT") # "Hello JT at CompanyB"

Reference

  • Ruby Programming ver.4

Comments