Last active
December 18, 2015 05:29
-
-
Save karolmajta/5732868 to your computer and use it in GitHub Desktop.
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 PathBuilder(object): | |
""" | |
Super awsome url path builder: | |
>>> PathBuilder().access_tokens.fold() | |
>>> "/access-tokens" | |
>>> PathBuilder().access_tokens.list().fold() | |
>>> "/access-tokens/" | |
>>> PathBuilder().access_tokens(30).fold() | |
>>> "/access-tokens/30" | |
>>> PathBuilder().access_tokens(30).related_actions.list().fold() | |
>>> "/access-tokens/30/related-actions/" | |
>>> PathBuilder().access_tokens(30).related_actions.main_action.fold() | |
>>> "/access-tokens/30/related-actions/main-action" | |
>>> PathBuilder().colors("warm").red.fold() | |
>>> "/colors/warm/red" | |
I hope you get it ;) | |
""" | |
def __init__(self): | |
self._chunks = [] | |
def __getattr__(self, name): | |
if name == "list": | |
return self.list | |
if name in self.__dict__: | |
return self.__dict__[name] | |
else: | |
new_chunk = unicode(name.replace("_", "-")) | |
self._chunks.append(new_chunk) | |
return self | |
def __call__(self, val): | |
self._chunks.append(unicode(val)) | |
return self | |
def list(self): | |
try: | |
self._chunks[-1] += u"/" | |
except IndexError: | |
pass | |
return self | |
def fold(self): | |
result = u"/" + u"/".join(self._chunks) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment