Lennakim

I am lennakim

0%

如何使用 ActiveSupport::Concern

在使用es-model的时候, include Elasticsearch::Model, model 就有了search方法, 代码如下:

/models/article.rb
1
2
3
4
5
6
class Article < ActiveRecord::Base
include Elasticsearch::Model
end

Article.search # is worked

如何通过ActiveSupport::Concern, 实现类似的功能呢?

test.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require 'active_support'

module Foo
extend ActiveSupport::Concern

def instance_method
puts "this is a instance_method"
end

included do
## 定义类方法
def self.class_method
puts "this is a class_method"
end
end
end

class Test
include Foo
end

Test.new.instance_method
Test.class_method

campo有相似代码

1
2
3
4
5
6
7
8
9
10
11
12
13

module Likeable
extend ActiveSupport::Concern

included do
has_many :likes, as: 'likeable', dependent: :delete_all
end

def liked_by?(user)
likes.where(user: user).exists?
end
end

这样的好处是: 1. 代码复用 2. 分拆代码, 使结构更清晰.

AS::Concern的另一个作用: 解决modules之间的dependencies, 可以参考 ihower的文章.