| Version 1 (modified by guest, 5 years ago) |
|---|
"Get By or Add" Pattern
Frequently when initializing data, one might find this particular pattern emerging:
my = MyEntity.get_by(name="John", email="john@example.com")
if not my:
# create it
my = MyEntity(name="John", email="john@example.com")
my.password = "default"
If you find you encounter this pattern frequently, try patching Elixir.Entity with the following:
from elixir import Entity
def get_by_or_init(cls, if_new_set={}, **params):
"""Call get_by; if no object is returned, initialize an
object with the same parameters. If a new object was
created, set any initial values."""
result = cls.get_by(**params)
if not result:
result = cls(**params)
result.set(**if_new_set)
return result
Entity.get_by_or_init = classmethod(get_by_or_init)
Now you may easily initialize your data with a simple single call and much less repetition.
my = MyEntity.get_by_or_init(
name="John",
email="john@example.com",
if_new_set=dict(password="default")
)
