Skip to content

Refactor use_course() #276

@jennybc

Description

@jennybc

Some code shared by @jeroen in a Slack conversation about use_course()

library(curl)

download_with_cd <- function(url, destdir = "."){
  h <- new_handle(noprogress = FALSE)
  tmp <- tempfile()
  curl::curl_fetch_disk(url, tmp, handle = h)
  headers <- curl::parse_headers_list(handle_data(h)$headers)
  filename <- stringr::str_match(headers[["content-disposition"]], "filename=.*")[1]
  filename <- sub("filename=", "", filename)
  outfile <- normalizePath(file.path(destdir, filename), mustWork = FALSE)
  file.rename(tmp, outfile)
  return(outfile)
}

download_with_cd("https://cran.ocpu.io/ggplot2/data/diamonds/csv", destdir = "~")

Other notes:

  • If you use curl_fetch_disk you can check the status code also from handle_data().
  • Using curl_download() might be easier -- automatically throws an error if the result is not http 200
  • the trick is all functions in curl take a handle, and you can always use handle_data() to access the metadata after the request

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurea feature request or enhancement

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions