2017-12-18

Ruby-style accessors in TclOO

A way to get Ruby-style accessors in TclOO. Inspired by code on the Tcl Wiki by “anonymous”, improved by Nathan Coulter. This code has been posted to the Wiki as well.

Accessors let you declare instance variables and getter and/or setter methods for them at the same time. The attr_reader and attr_accessor commands declare one or more variables and also methods for them with the same name, which return the current value of the variable. The attr_writer and attr_accessor commands declare one or more variables and also methods for them with the same name with an appended =, which take a value argument and set the variable to that value. So attr_accessor foo bar  declares the variables foo and bar , the getter methods foo and bar , and the setter methods foo= and bar=

namespace eval oo::define {
    proc attr {access args} {
        set class [lindex [info level -1] 1]
        ::oo::define $class variable {*}$args
        if {"reader" in $access} {
            foreach name $args {
                ::oo::define $class method $name {} \
                    [format {set %s} $name]
            }
        }
        if {"writer" in $access} {
            foreach name $args {
                ::oo::define $class method $name= v \
                    [format {set %s $v} $name]
            }
        }
    }
     
    interp alias {} attr_reader {} ::oo::define::attr reader
    interp alias {} attr_writer {} ::oo::define::attr writer
    interp alias {} attr_accessor {} ::oo::define::attr {reader writer}
}

Usage:

oo::class create Foo {
    attr_reader a
    attr_accessor b c
    constructor {} {set a 99}
}

% Foo create o
::o
% o a
99
% o b= 33
33
% o b
33
% o c
can't read "c": no such variable

Documentation: foreach, format, if, in (operator), info, interp, lindex, method (class configuration subcommand), oo::class, oo::define, proc, set, variable (class slot subcommand), {*} (syntax)

No comments:

Post a Comment