Skip to content

Commit 2a508bb

Browse files
committed
Adds a way to register custom formatters
1 parent b3daf56 commit 2a508bb

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

pendulum/formatting/__init__.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# -*- coding: utf-8 -*-
22

3+
from .formatter import Formatter
34
from .classic_formatter import ClassicFormatter
45
from .alternative_formatter import AlternativeFormatter
56

@@ -8,3 +9,27 @@
89
'classic': ClassicFormatter(),
910
'alternative': AlternativeFormatter(),
1011
}
12+
13+
14+
def register_formatter(name, formatter):
15+
"""
16+
Register a new formatter.
17+
18+
:param name: The name of the formatter.
19+
:type name: str
20+
21+
:param formatter: The formatter instance
22+
:type formatter: Formatter
23+
24+
:rtype: None
25+
"""
26+
if name in FORMATTERS:
27+
raise ValueError('Formatter [{}] already exists'.format(name))
28+
29+
if not isinstance(formatter, Formatter):
30+
raise ValueError(
31+
'The formatter instance '
32+
'must be an instance of Formatter'
33+
)
34+
35+
FORMATTERS[name] = formatter
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import pendulum
4+
from .. import AbstractTestCase
5+
6+
from pendulum.formatting import register_formatter, Formatter
7+
8+
9+
class ModuleTestCase(AbstractTestCase):
10+
11+
def test_register_formatter(self):
12+
register_formatter('test', TestFormatter())
13+
14+
self.assertEqual('foo', pendulum.now().format('', formatter='test'))
15+
16+
def test_register_formatter_existing_name(self):
17+
self.assertRaises(ValueError, register_formatter, 'classic', TestFormatter())
18+
19+
def test_register_formatter_not_formatter_instance(self):
20+
self.assertRaises(ValueError, register_formatter, 'test', FooFormatter())
21+
22+
23+
class TestFormatter(Formatter):
24+
25+
def format(self, dt, fmt, locale=None):
26+
return 'foo'
27+
28+
29+
class FooFormatter(object):
30+
31+
def format(self, dt, fmt, locale=None):
32+
return 'foo'
33+
34+

0 commit comments

Comments
 (0)