Skip to content

Instantly share code, notes, and snippets.

@abom
Created April 16, 2020 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abom/1b06056aba7641452c34ce457398da6a to your computer and use it in GitHub Desktop.
Save abom/1b06056aba7641452c34ce457398da6a to your computer and use it in GitHub Desktop.
a factory with name mapping for js-ng
"""
Redis client
"""
from jumpscale.core.base import Base, StoredFactory
from jumpscale.core.base import fields
class Project(Base):
name = fields.String()
total_tasks = fields.Integer()
def map_name(method):
def inner(self, name, *args, **kwargs):
if not name:
return method(name, *args, **kwargs)
if not name.startswith('__'):
instance = method(self, self.get_identifier(name), *args, **kwargs)
if hasattr(instance, "name"):
instance.name = name
else:
instance = method(self, name, *args, **kwargs)
return instance
return inner
class CustomFactory(StoredFactory):
def get_identifier(self, name):
"""returns a new unique name that can be used as an identifier"""
hashed = j.data.hash.md5(name)
# prefix this hashed value, so it will be hidden
# and also always a str (md5 can start with a number)
return f"__{hashed}"
@map_name
def find(self, name):
return super().find(name)
@map_name
def new(self, name, *args, **kwargs):
instance = super().new(name, *args, **kwargs)
return instance
@map_name
def get(self, name, *args, **kwargs):
return super().get(name, *args, **kwargs)
def list_all(self):
names = super().list_all()
return [self.get(name).name for name in names]
class Account(Base):
name = fields.String()
projects = fields.Factory(Project, factory_type=CustomFactory)
accounts = CustomFactory(Account)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment