Version 6 of ensemble extend

Updated 2006-03-06 00:01:15

Here's a simple bit of code to extend any ensemble-like command by means of tcl8.5's namespace ensemble command. CMcC 6Mar2006

 package provide extend 1.0
 package require Tcl 8.5

    # extend a command with a new subcommand
    proc extend {cmd body} {
        if {![namespace exists ${cmd}]} {
            set wrapper [string map [list %C $cmd %B $body] {
                namespace eval %C {}
                rename %C %C::%C
                namespace eval %C {
                    proc _unknown {junk subc args} {
                        return [list %C::%C $subc]
                    }
                    namespace ensemble create -unknown %C::_unknown
                }
            }]
        }

        append wrapper [string map [list %C $cmd %B $body] {
            namespace eval %C {
                %B
                namespace export -clear *
            }
        }]
        uplevel 1 $wrapper
    }

Here's the file command extended with newer and newerthan subcommands:

 extend file {
    proc newer {a b} {
       return [expr {[file mtime $a] > [file mtime $b]}]
    }

    proc newerthan {mtime path} {
       return [expr {[file exists $path] && ([file mtime $path] > $mtime)}]
    }
 }

Here's the dict command extended with the modify subcommand:

 # extra useful dict commands
 extend dict {
    proc modify {var args} {
       upvar 1 $var dvar
       foreach {name val} $args {
          dict set dvar $name $val
       }
    }
 }


[Category ???] quick hacks ?