Created
October 9, 2012 07:29
-
-
Save asv/3857175 to your computer and use it in GitHub Desktop.
pbx mask formatter class (prototype)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MaskFormatter(object): | |
def __init__(self, **variables): | |
self.variables = variables | |
self.formatter = string.Formatter() | |
def format(self, match_pattern, strip_length, prepend_prefix): | |
mask_parts = [] | |
for literal_text, field_name, _, _ in self.formatter.parse(prepend_prefix): | |
if literal_text: | |
mask_parts.append(literal_text) | |
if field_name and field_name in self.variables: | |
mask_parts.append(unicode(self.variables[field_name])) | |
for literal_text, field_name, _, _ in self.formatter.parse(match_pattern): | |
if literal_text: | |
if strip_length: | |
literal_text_len = len(literal_text) | |
if literal_text_len >= strip_length: | |
literal_text = literal_text[strip_length:] | |
strip_length = 0 | |
else: | |
strip_length -= literal_text_len | |
mask_parts.append(literal_text) | |
if field_name and field_name in self.variables: | |
if strip_length: | |
strip_length -= 1 | |
else: | |
mask_parts.append(unicode(self.variables[field_name])) | |
return ''.join(mask_parts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment