Let's say I have a simple abstract R6
class.
myClass <- R6::R6Class(
classname = "myClass",
public = list(
save = function(path) {
saveRDS(self, path)
},
load = function(path) {
object <- readRDS(path)
self <- object
lockEnvironment(self)
invisible(self)
}
)
)
Then I have a child class which does some stuff
myChildClass <- R6::R6Class(
classname = "myChildClass",
inherit = myClass,
lock_objects = FALSE,
public = list(
initialize = function(x) {
private$x <- x
},
addOne = function() {
private$x <- private$x + 1
private$x
}
),
private = list(x = NA_real_)
)
What I want to do is be able to save my created class and then reinstantiate it at a later time.
tmp <- myChildClass$new(x = 10)
tmp$addOne()
tmp$addOne()
tmpFile <- tempfile()
tmp$save(tmpFile)
new <- myClass$new()
new$load(tmpFile)
new
# <myClass>
# Public:
# clone: function (deep = FALSE)
# load: function (path)
# save: function (path)
The problem that I have is that for some reason self
is not actually updated when we call $load()
. If I debug the method, I see that it does get overwritten, but the object new
still returns the initial myClass
object without the loaded changes. The only way I can seem to get this to do what I want is by reassigning the output (obviously).
new <- myClass$new()
new <- new$load(tmpFile)
new
# <myChildClass>
# Inherits from: <myClass>
# Public:
# addOne: function ()
# clone: function (deep = FALSE)
# initialize: function (x)
# load: function (path)
# save: function (path)
# Private:
# x: 12
Now I understand that I can just readRDS()
and be done with it but I want this to be chainable, hence trying to place this in a method.