From 559eb725e643ba4903ef509a0cae892ad529a733 Mon Sep 17 00:00:00 2001 From: James Turk Date: Mon, 28 Jun 2010 21:03:30 -0400 Subject: [PATCH] ConditionalPathFilter --- saucebrush/filters.py | 14 ++++++++++++++ saucebrush/tests/filters.py | 15 ++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/saucebrush/filters.py b/saucebrush/filters.py index 4f7786f..d7e3b2a 100644 --- a/saucebrush/filters.py +++ b/saucebrush/filters.py @@ -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 ## ##################### diff --git a/saucebrush/tests/filters.py b/saucebrush/tests/filters.py index e138f32..cbd9cd7 100644 --- a/saucebrush/tests/filters.py +++ b/saucebrush/tests/filters.py @@ -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):