I have some code that I want to run when a user loads my package. That code includes creating a reference class (Parent) and source
ing a file stored under inst
. Here is a toy version:
Parent <- setRefClass("Parent",
methods = list(
initialize = function() { }
)
)
.onLoad <- function(libname, pkgname){
temp <- new.env()
file <- system.file("example.R", package = "examplerefclass")
sys.source(file, envir = temp)
objects <- ls(temp)
print(objects)
}
example.R
file defines a reference class.
library(methods)
Child <- setRefClass("Child", contains = "Parent")
I had to call library(methods)
because the methods
package is not defined when .onLoad
runs. So, this works, but I get an error when I run R CMD check
and I don't know how to avoid it.
Error : .onLoad failed in loadNamespace() for 'examplerefclass', details:
call: initialize(value, ...)
error: attempt to apply non-function
The error refers to the initialize
function defined in Parent
. Somehow, the Child
class is not seeing it during the R CMD check
process, but it works in interactive mode.
I know what I'm doing is unconventional but I don't see any other way to meet my design requirements. For a number of reasons example.R
must be stored in inst
, and I need to check what objects
are defined in example.R
without sourcing it in the current environment (if the right objects are defined, I then go on to source example.R
but that is another story).
Any suggestions on how to fix this?
I've set up the toy example in a git repo for easy testing: https://github.com/nachocab/examplerefclass