distributing R package with optional dependencies
I've written a small package for logging, I'm distributing it through r-forge, recently I received some very interesting feedback on how to make it easier to use, but this functionality is based on stuff (setRefClass
) that was added to R in 2.12.
I'd like to keep distributing the package also for R-2.11, so I'm looking for a way to include or exclude the S4 syntactical sugar automatically, and include it when the library is loaded on a R >= 2.12 system.
one other option I see, 开发者_开发技巧that is to write a small S4 package that needs 2.12, imports the simpler logging
package and exports the syntactically sugared interface... I don't like it too much, as I'd need to choose a different name for the S4 package.
thank you, Gabor, for offering a way to avoid this need but the question is still open.
This could be done with the proto package. This supports older versions of R (its been around for years) so you would not have a problem of old vs. new versions of R.
library(proto)
library(logging)
Logger. <- proto(
new = function(this, name)
this$proto(name = name),
log = function(this, ...)
levellog(..., logger = this$name),
setLevel = function(this, newLevel)
logging::setLevel(newLevel, container = this$name),
addHandler = function(this, ...)
logging::addHandler(this, ..., logger = this$name),
warn = function(this, ...)
this$log(loglevels["WARN"], ...),
error = function(this, ...)
this$log(loglevels["ERROR"], ...)
)
basicConfig()
l <- Logger.$new(name = "hierarchic.logger.name")
l$warn("this may be bad")
l$error("this definitely is bad")
This gives the output:
> basicConfig()
> l <- Logger.$new(name = "hierarchic.logger.name")
> l$warn("this may be bad")
2011-02-28 10:17:54 WARNING:hierarchic.logger.name:this may be bad
> l$error("this definitely is bad")
2011-02-28 10:17:54 ERROR:hierarchic.logger.name:this definitely is bad
In the above we have merely layered proto on top of logging but it would be possible to turn each logging object into a proto object, i.e. it would be both, since both logging objects and proto objects are R environments. That would get rid of the extra layer.
See the http://r-proto.googlecode.com for more info.
精彩评论