fields.on_changes no requiere un nombre especifico para su ejecucion

FossilOrigin-Name: 55d11605df9d1228737da18bf04b242fff3b08939021488f169ad2b042330d6f
This commit is contained in:
bit4bit 2021-06-26 20:25:07 +00:00
parent bd25bef21f
commit 53b5207e35
3 changed files with 13 additions and 14 deletions

View File

@ -23,17 +23,17 @@ class ModelBase(object, metaclass=ModelMeta):
obj._namespace_prefix = None
obj._on_change_fields = defaultdict(list)
def on_change_fields_for_function(function_name):
def on_change_fields_for_function():
# se recorre arbol buscando el primero
for parent_cls in type(obj).__mro__:
parent_meth = getattr(parent_cls, function_name, None)
if not parent_meth:
continue
on_changes = getattr(parent_meth, 'on_changes', None)
if on_changes:
return on_changes
return []
for parent_attr in dir(parent_cls):
parent_meth = getattr(parent_cls, parent_attr, None)
if not callable(parent_meth):
continue
on_changes = getattr(parent_meth, 'on_changes', None)
if on_changes:
return (parent_meth, on_changes)
return (None, [])
# forzamos registros de campos al modelo
# al instanciar
@ -43,10 +43,9 @@ class ModelBase(object, metaclass=ModelMeta):
setattr(obj, key, v.default)
# register callbacks for changes
function_name = 'on_change_%s' % (key)
on_change_fields = on_change_fields_for_function(function_name)
(fun, on_change_fields) = on_change_fields_for_function()
for field in on_change_fields:
obj._on_change_fields[field].append(function_name)
obj._on_change_fields[field].append(fun)
return obj

View File

@ -47,5 +47,5 @@ class Field:
def _changed_field(self, inst, name, value):
for fun in inst._on_change_fields[name]:
getattr(inst, fun)(name, value)
fun(inst, name, value)

View File

@ -391,7 +391,7 @@ def test_model_on_change_field_attribute():
hash = fields.Attribute('Hash')
@fields.on_change(['hash'])
def on_change_react(self, name, value):
def on_react(self, name, value):
assert name == 'hash'
self.react = "%s+4" % (value)