Skip to content

Commit b0f4865

Browse files
author
luodaokai
committed
ES params DSL build ES query params
1 parent 9cdc7e1 commit b0f4865

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

simple_way_build_es_param.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class ESParamsDsl
2+
def initialize
3+
@hash = {}
4+
end
5+
6+
# 使用method_missing 方法的灵活性
7+
def method_missing method_name, key=nil, value=nil, &block
8+
if block_given?
9+
new_instance = self.class.new # ESParamsDsl.new
10+
new_instance.instance_eval(&block) # 执行block中的逻辑,由于block中也触发method_missing方法,所以这里形成了递归
11+
@hash[method_name] = new_instance.to_params # to_params 方法中的@hash和外面的@hash不是同一个
12+
else # 递归结束条件就是 不再是block块代码
13+
@hash[method_name] ||= {}
14+
@hash[method_name][key] = value # 返回最里层的 hash结构
15+
end
16+
end
17+
18+
def to_params # 返回当前的hash结构, 方法中的@hash和外面的@hash不是同一个
19+
@hash
20+
end
21+
end
22+
23+
es_params = ESParamsDsl.new
24+
25+
es_params.bool do
26+
must do
27+
match 'title', 'test'
28+
term 'age', 27
29+
end
30+
end
31+
32+
puts es_params.to_params
33+
34+
# 每一个block 就是一个hash结构

0 commit comments

Comments
 (0)