Skip to content

Commit

Permalink
#31 include namespace exporting and simplified function names
Browse files Browse the repository at this point in the history
  • Loading branch information
jmbarbone committed Jul 21, 2023
1 parent 443b773 commit f4dcc53
Showing 1 changed file with 45 additions and 26 deletions.
71 changes: 45 additions & 26 deletions R/colons.R
Original file line number Diff line number Diff line change
@@ -1,51 +1,70 @@
#' Colons
#'
#' Get an object from a package
#' Get an object from a namespace
#'
#' @details
#' This is a work around to calling `:::`.
#' @details The functions mimic the use of `::` and `:::` for extracting values
#' from namespaces. `%colons%` is an alias for `%::%`.
#'
#' @section WARNING:
#' To reiterate from other documentation: it is not advised to use `:::` in
#' your code as it will retrieve non-exported objects that may be more
#' likely to change in their functionality that exported objects.
#' @section WARNING: To reiterate from other documentation: it is not advised to
#' use `:::` in your code as it will retrieve non-exported objects that may be
#' more likely to change in their functionality that exported objects.
#'
#' @param package Name of the package
#' @param name Name to retrieve
#' @return The variable `name` from package `package`
#' @examples
#' identical("base" %colons% "mean", base::mean)
#' "fuj" %colons% "colons_example" # unexported value
#' identical("base" %::% "mean", base::mean)
#' "fuj" %:::% "colons_example" # unexported value
#'
#' @name colons
#' @seealso `help("::")`
NULL

#' @rdname colons
#' @export
`%colons%` <- function(package, name) {
stopifnot(
length(package) == 1,
is.character(package),
length(name) == 1,
is.character(name)
`%::%` <- function(package, name) {
colons_check(package, name)
tryCatch(
getExportedValue(asNamespace(package), name),
error = function(e) stop(cond_colons(package, name, 2))
)
}

require_namespace(package)

res <- try(get(name, envir = asNamespace(package)), silent = TRUE)

if (inherits(res, "try-error")) {
stop(cond_colons(package, name))
}

res
#' @rdname colons
#' @export
`%:::%` <- function(package, name) {
colons_check(package, name)
tryCatch(
get(name, envir = asNamespace(package)),
error = function(e) stop(cond_colons(package, name, 3))
)
}

cond_colons <- function(package, name) {
#' @rdname colons
#' @export
`%colons%` <- `%:::%`

cond_colons <- function(package, name, n) {
new_condition(
msg = sprintf(
"`%s:::%s` not found",
"`%s%s%s` not found",
as.character(package),
strrep(":", n),
as.character(name)
),
class = "colons"
)
}

colons_check <- function(package, name) {
stopifnot(
length(package) == 1,
is.character(package),
length(name) == 1,
is.character(name)
)

require_namespace(package)
}

colons_example <- "Hello, world"

0 comments on commit f4dcc53

Please sign in to comment.