Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attach resource's data #274

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions R/read_package.R
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#' Data Package standard.
#'
#' @param file Path or URL to a `datapackage.json` file.
#' @param attach Attach the resources' data to the package object rather than keeping the path. See
#' [data location](https://specs.frictionlessdata.io/data-resource/#data-location).
#' @return A Data Package object, see [create_package()].
#' @family read functions
#' @export
Expand All @@ -22,7 +24,7 @@
#' # Access the Data Package properties
#' package$name
#' package$created
read_package <- function(file = "datapackage.json") {
read_package <- function(file = "datapackage.json", attach = FALSE) {
# Read file
if (!is.character(file)) {
cli::cli_abort(
Expand All @@ -48,5 +50,19 @@ read_package <- function(file = "datapackage.json") {
descriptor$directory <- dirname(file) # Also works for URLs

# Create package
create_package(descriptor)
package <- create_package(descriptor)

# Attach path and url to package
if (attach) {
package$resources <- purrr::map(package$resources, ~ {
resource <- get_resource(package, .x$name)
if (resource$read_from %in% c("path", "url")) {
.x$data <- read_from_path(package, .x$name, col_select = NULL)
.x$path <- NULL
}
.x
})
}

return(package)
}
14 changes: 14 additions & 0 deletions tests/testthat/test-read_package.R
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,17 @@ test_that("read_package() converts JSON null to NULL", {
# { "image": null } is read as NULL (use chuck() to force error if missing)
expect_null(purrr::chuck(p, "image"))
})


test_that("read_package() with `attach=TRUE`", {
p_path <- system.file("extdata", "v1", "datapackage.json", package = "frictionless")
p <- read_package(p_path, attach = TRUE)
expect_s3_class(p$resources[[1]]$data, "data.frame")

p_url <- file.path(
"https://raw.githubusercontent.com/frictionlessdata/frictionless-r/",
"main/inst/extdata/v1/datapackage.json"
)
p_remote <- read_package(p_url, attach = TRUE)
expect_s3_class(p_remote$resources[[1]]$data, "data.frame")
})