Version 5 of ensemble extend

Updated 2006-03-05 23:36:08

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} {
    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]
          }
          %B
          namespace export -clear *
          namespace ensemble create -unknown %C::_unknown
       }
    }]
    uplevel \#0 $wrapper
 }

Improvements:

  1. should not necessarily assume global scope for commands,
  2. rename and _unknown definition should be protected by a test, so multiple serial [extend] invocations work.

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 ?