Created
June 30, 2012 21:37
-
-
Save barryrowlingson/3025606 to your computer and use it in GitHub Desktop.
Simple mechanism for attaching functions in a single .R file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
### tach (c) Barry Rowlingson, 2012, pronounced like "tash" | |
### | |
### tach("file.R") will source that file into an environment and | |
### put it on the search path, thus including any function | |
### definitions without polluting your GlobalEnv | |
### | |
### retach() will scan your search path for any tach'ed files and | |
### if they have been modified since they were loaded they'll be | |
### re-tached. | |
### | |
### To remove, just use detach(pos) where pos is the position | |
### | |
### until this makes it into a package (or oblivion) you can do: | |
### | |
### source("tach.R");tach("tach.R");rm(tach,retach) | |
### | |
### and then you've tach'ed tach itself and cleaned up. | |
### | |
### TODO: check for multiple taching the same file | |
### verbosity reporting | |
### smarter detach | |
### print method for fileenv | |
### tach whole directories of .R files. But that's nearly a package. | |
tach <- function(file){ | |
### | |
### source a file into an environment and attach | |
### to the search path | |
### | |
e = new.env() | |
source(file,e) | |
me = attach(e,name=sprintf("file:%s",file)) | |
### | |
### superclass it and add some metadata | |
### | |
class(me)=c("fileenv","environment") | |
attr(me,"src")=normalizePath(file) | |
attr(me,"loaded")=Sys.time() | |
} | |
retach <- function(){ | |
### scan the search path for fileenv class objects | |
s = search() | |
for(pos in 1:length(s)){ | |
e = pos.to.env(pos) | |
if(inherits(e,"fileenv")){ | |
## look for modification since last source | |
cat(s[pos]," is a file env\n") | |
when = attr(e,"loaded") | |
fmod = file.info(attr(e,"src"))$mtime | |
if(when < fmod){ | |
## re-source it, update timestamp | |
cat(s[pos], " changed since load\n") | |
remove(list = ls(e),envir=e) | |
source(attr(e,"src"),e) | |
attr(e,"loaded")=Sys.time() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment