Ruby/rails / 链接方法
Ruby/rails / chaining methods
给定以下示例:
apply_filter_a(
apply_filter_b(
apply_filter_c(
active_record_dataset
)
)
)
...
def apply_filter_a(records)
# some more complex than
...
end
def apply_filter_b(records)
# some other complex logic filtering the active record dataset
...
end
def apply_filter_c(records)
# some other complex logic filtering the active record dataset
...
end
如何以更简单的方式简化嵌套方法语法(apply_filter_a(apply_filter_b(...
))?是否可以应用一组方法中的方法?
你可以用Enumerable#inject
做这种折叠操作。
首先,我们需要一组方法。我们可以使用 method
.
my_filters = [method(:apply_filter_c), method(:apply_filter_b), method(:apply_filter_a)]
然后我们可以在过滤器列表中使用 inject
来应用初始值。
my_filters.inject(active_record_dataset) { |acc, f| f.call acc }
还有yield_self
method, or you can use its alias then
。您可以一个接一个地通过管道调用,每个筛选方法都必须 return 一个活动记录关系。
apply_filter_a(active_record_dataset)
.then { |records| apply_filter_b(records) }
.then { |records| apply_filter_c(records) }
给定以下示例:
apply_filter_a(
apply_filter_b(
apply_filter_c(
active_record_dataset
)
)
)
...
def apply_filter_a(records)
# some more complex than
...
end
def apply_filter_b(records)
# some other complex logic filtering the active record dataset
...
end
def apply_filter_c(records)
# some other complex logic filtering the active record dataset
...
end
如何以更简单的方式简化嵌套方法语法(apply_filter_a(apply_filter_b(...
))?是否可以应用一组方法中的方法?
你可以用Enumerable#inject
做这种折叠操作。
首先,我们需要一组方法。我们可以使用 method
.
my_filters = [method(:apply_filter_c), method(:apply_filter_b), method(:apply_filter_a)]
然后我们可以在过滤器列表中使用 inject
来应用初始值。
my_filters.inject(active_record_dataset) { |acc, f| f.call acc }
还有yield_self
method, or you can use its alias then
。您可以一个接一个地通过管道调用,每个筛选方法都必须 return 一个活动记录关系。
apply_filter_a(active_record_dataset)
.then { |records| apply_filter_b(records) }
.then { |records| apply_filter_c(records) }