Skip to content

Commit

Permalink
Merge pull request #79 from tidymodels/backwards-json
Browse files Browse the repository at this point in the history
make orbital_json_* functions backwards compatible
  • Loading branch information
EmilHvitfeldt authored Dec 21, 2024
2 parents 287ea9d + 07b4328 commit 3b86035
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
19 changes: 16 additions & 3 deletions R/json.R
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@
orbital_json_write <- function(x, path) {
actions <- as.list(unclass(x))

res <- list(actions = actions, version = 1)
res <- list(
actions = actions,
pred_names = attr(x, "pred_names"),
version = 2
)

res <- jsonlite::toJSON(res, pretty = TRUE, auto_unbox = TRUE)

writeLines(res, path)
Expand Down Expand Up @@ -85,9 +90,17 @@ orbital_json_write <- function(x, path) {
orbital_json_read <- function(path) {
rlang::check_installed("jsonlite")

res <- jsonlite::read_json(path)
json <- jsonlite::read_json(path)

version <- json$version

res <- unlist(res$actions)
if (version == 1) {
res <- unlist(json$actions)
attr(res, "pred_names") <- utils::tail(names(res), 1)
} else if (version == 2) {
res <- unlist(json$actions)
attr(res, "pred_names") <- json$pred_names
}

new_orbital_class(res)
}
33 changes: 31 additions & 2 deletions tests/testthat/test-json.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,37 @@ test_that("read and write json works", {

new <- orbital_json_read(tmp_file)

# temp fix
attr(orbital_obj, "pred_names") <- NULL
expect_identical(new, orbital_obj)
})

test_that("read and write json works - backwards from version 1", {
skip_if_not_installed("recipes")
skip_if_not_installed("tidypredict")
skip_if_not_installed("jsonlite")
skip_if_not_installed("workflows")
rec_spec <- recipes::recipe(mpg ~ ., data = mtcars) %>%
recipes::step_normalize(recipes::all_numeric_predictors())

lm_spec <- parsnip::linear_reg()

wf_spec <- workflows::workflow(rec_spec, lm_spec)

wf_fit <- parsnip::fit(wf_spec, mtcars)

orbital_obj <- orbital(wf_fit)

tmp_file <- tempfile()

orbital_json_write(orbital_obj, tmp_file)

# Fake version 1
fake_json <- jsonlite::read_json(tmp_file)
fake_json$pred_names <- NULL
fake_json$version <- 1
fake_json <- jsonlite::toJSON(fake_json, pretty = TRUE, auto_unbox = TRUE)
writeLines(fake_json, tmp_file)

new <- orbital_json_read(tmp_file)

expect_identical(new, orbital_obj)
})

0 comments on commit 3b86035

Please sign in to comment.