R: proto serialization/deserialization to list
-
27-06-2021 - |
Question
I'd like to be able to store some simple proto
objects in a persistent store (MongoDB) where their properties can be manipulated by code from other programming languages. By simple I mean that they will not refer to other proto objects. Their properties will be common R types: lists, vectors, etc. Further, each object can have a factory method that creates it given a list with its property values. Therefore the MongoDB-to-proto path seems straightforward.
I don't understand proto
's internals and R environment chaining well-enough to know whether there is a simple and robust way to get all the proto object's properties as an R list. Can this be done automatically or should I be thinking about all proto objects implementing something like a to_list()
method?
Some example code using testthat
and a new MongoDB driver API I am developing about the behavior I'd like to see here:
test_that("proto persistence", {
Person <- proto(
..Name = 'PersonFactory',
has_tag = function(., tag) {
tag %in% .$tags
},
new = function(., name, tags=c()) {
.$proto(..Name='Person', name=name, tags=tags)
}
)
p1 <- Person$new(name='bob', tags=c('friend', 'coworker'))
coll <- test_db()$collection('test')
coll$store('bob', p1)
result <- coll$find_one(id='bob')
expect_true(is.list(result))
expect_true(is.list(result$proto))
expect_equal(result$proto$name, 'bob')
expect_equal(result$proto$tags, c('friend', 'coworker'))
p2 <- coll$load('bob')
expect_equal(p2$name, 'bob')
expect_equal(p2$tags, c('friend', 'coworker'))
expect_true(p2$has_tag('friend'))
})
Solution
To turn p1
from the question into a list. L1
:
L1 <- as.list(p1)
and to turn it back into a proto object, p1a
, whose parent is Person
:
p1a <- as.proto(L1, parent = Person)
You can then build whatever structure you want around these basics.