Given the following example :
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
How to simplify the nested method syntax (apply_filter_a(apply_filter_b(...
)) in a more simple way ? is it possible to apply methods from an array of methods ?
CodePudding user response:
You can do this sort of folding operation with Enumerable#inject
.
First, we need an array of methods. We can get those using method
.
my_filters = [method(:apply_filter_c), method(:apply_filter_b), method(:apply_filter_a)]
Then we can use inject
on the list of filters to apply to an initial value.
my_filters.inject(active_record_dataset) { |acc, f| f.call acc }
CodePudding user response:
There is the yield_self
, or you can use its alias then
. You can pipe calls one by one, each of your filter methods must return an active record relation.
apply_filter_a(active_record_dataset)
.then { |records| apply_filter_b(records) }
.then { |records| apply_filter_c(records) }