ConditionalPathFilter
This commit is contained in:
parent
18a15022a5
commit
559eb725e6
@ -172,6 +172,20 @@ class SubrecordFilter(Filter):
|
||||
self.process_subrecord(subrecord_parent)
|
||||
return record
|
||||
|
||||
class ConditionalPathFilter(Filter):
|
||||
""" Filter that uses a predicate to split input among two filter paths. """
|
||||
|
||||
def __init__(self, predicate_func, true_filter, false_filter):
|
||||
self.predicate_func = predicate_func
|
||||
self.true_filter = true_filter
|
||||
self.false_filter = false_filter
|
||||
|
||||
def process_record(self, record):
|
||||
if self.predicate_func(record):
|
||||
return self.true_filter.process_record(record)
|
||||
else:
|
||||
return self.false_filter.process_record(record)
|
||||
|
||||
#####################
|
||||
## Generic Filters ##
|
||||
#####################
|
||||
|
@ -2,7 +2,7 @@ import unittest
|
||||
import operator
|
||||
import types
|
||||
from saucebrush.filters import (Filter, YieldFilter, FieldFilter,
|
||||
SubrecordFilter,
|
||||
SubrecordFilter, ConditionalPathFilter,
|
||||
ConditionalFilter, FieldModifier,
|
||||
FieldRemover, FieldMerger, FieldAdder,
|
||||
FieldCopier, FieldRenamer, Unique)
|
||||
@ -175,6 +175,19 @@ class FilterTestCase(unittest.TestCase):
|
||||
|
||||
self.assertEquals(list(result), expected)
|
||||
|
||||
def test_conditional_path(self):
|
||||
|
||||
predicate = lambda r: r['a'] == 1
|
||||
|
||||
# double b if a == 1, otherwise double c
|
||||
cpf = ConditionalPathFilter(predicate, FieldDoubler('b'),
|
||||
FieldDoubler('c'))
|
||||
expected_data = [{'a':1, 'b':4, 'c':3},
|
||||
{'a':5, 'b':5, 'c':10},
|
||||
{'a':1, 'b':20, 'c':100}]
|
||||
|
||||
self.assert_filter_result(cpf, expected_data)
|
||||
|
||||
### Tests for Generic Filters
|
||||
|
||||
def test_field_modifier(self):
|
||||
|
Loading…
Reference in New Issue
Block a user