Hi!
I need a way to validate the value during attribute assignment for an object.
Using macros as pragmas sounds like a good idea, and the syntax would be sane
and clear:
{.this: self.}
type
Person* = ref object of RootObj
name: string
proc name*(self: Person): string = name
proc `name=`*(self: var Person, value: string) {.maxLength: 100.} =
name = value
proc newPerson*(name: string, age: int = 0): Person =
new result
result.name = name
The `maxLength` macro would look something like this:
macro maxLength*(limit: Natural, setterProc: untyped): untyped =
let lengthValidation = quote do: # This is the part I
can't figure out.
if value > limit: # Obviously, this
doesn't work since: value is undeclared,
raise newException(ValidationError, "Too long") # and even if I
extract the variable from ``setterProc``, its value is unknown
setterProc.body.insert(0, lengthValidation)
result = setterProc
I can't figure out how to extract the runtime value of the `value` argument.
Maybe my approach is totally wrong. If you have a better suggestion, please
adviseāI'm a novice and am very keen to learn from pros.
I come from the Python background, so I'm viewing macro in this example sort of
like a decorator. I know they're very much different, but I don't know a better
alternative to decorators or can't find a better programming pattern for the
task. Again, any advice is appreciated.