文章目录
  1. 1. 目标:
  2. 2. 步骤:
    1. 2.1. Step 01:
    2. 2.2. Step 02:
  3. 3. 更多ROR【豆知识】:

目标:

不使用ActiveSupport::Concern模块怎样实现Module的Mixin

步骤:

Step 01:

大多时候我们封装Module时都这样写:

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
module A
extend ActiveSupport::Concern
included do
class_attribute :attr_name
end
def hello
p 'hello'
end
class_methods do
def hi
p 'hi'
end
end
end
class B
include A
end
B.attr_name = 'a'
B.attr_name
=> 'a'
B.hi
=> 'hi'
B.new.hello
=> 'hello'

如果不使用ActiveSupport::Concern模块怎样实现同样的功能?

Step 02:

如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
module A
def self.included(base)
base.extend ClassMethods
base.class_eval do
class_attribute :attr_name
end
end
def hello
p 'hello'
end
module ClassMethods
def hi
p 'hi'
end
end
end
class B
include A
end

更多ROR【豆知识】:

更多ROR【豆知识】请前往:https://github.com/Kerzzi/ruby_notes/tree/master/04_ROR_beans

文章目录
  1. 1. 目标:
  2. 2. 步骤:
    1. 2.1. Step 01:
    2. 2.2. Step 02:
  3. 3. 更多ROR【豆知识】: