【豆知识】rails: 不使用activesupport::concern模块怎样实现module的mixin

文章目录

目标:

不使用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
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
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