R/register_s3.R

Defines functions register_s3_method

Documented in register_s3_method

#' Register S3 Methods from External Packages
#'
#' https://github.com/tidyverse/hms/blob/master/R/zzz.R
#'
#' @param pkg Package name.
#' @param generic Generic function name.
#' @param class Class name.
#' @param fun Optional custom function name.
#'
#' @return None
register_s3_method <- function(pkg, generic, class, fun = NULL) {
  stopifnot(is.character(pkg), length(pkg) == 1)
  stopifnot(is.character(generic), length(generic) == 1)
  stopifnot(is.character(class), length(class) == 1)

  if (is.null(fun)) {
    fun <- get(paste0(generic, ".", class), envir = parent.frame())
  } else {
    stopifnot(is.function(fun))
  }

  if (pkg %in% loadedNamespaces()) {
    registerS3method(generic, class, fun, envir = asNamespace(pkg))
  }

  setHook(
    packageEvent(pkg, "onLoad"),
    function(...) {
      registerS3method(generic, class, fun, envir = asNamespace(pkg))
    }
  )
}

Try the copre package in your browser

Any scripts or data that you put into this service are public.

copre documentation built on May 29, 2024, 7:36 a.m.