diff --git a/NEWS.md b/NEWS.md index 61b78c756..dcc6b9aac 100644 --- a/NEWS.md +++ b/NEWS.md @@ -196,6 +196,7 @@ Thanks to Yihui and other developers for their helpful discussions around this issue (#797, @IndrajeetPatil). * The output of `lint()` and `Lint()` gain S3 class `"list"` to assist with S3 dispatch (#1494, @MichaelChirico) + + As a corollary, we now register an `as_tibble` method for class `lints`, conditional on {tibble} availability, to avoid dispatching to the `list` method which does not work with `lint()` output (#1997, @MichaelChirico) * `object_usage_linter()` gives a more helpful warning when a `glue()` expression fails to evaluate (#1985, @MichaelChirico) diff --git a/R/methods.R b/R/methods.R index 25726366f..af23f4d62 100644 --- a/R/methods.R +++ b/R/methods.R @@ -173,6 +173,14 @@ as.data.frame.lints <- function(x, row.names = NULL, optional = FALSE, ...) { # ) } +as_tibble.lints <- function(x, ..., # nolint: object_name_linter. + .rows = NULL, + .name_repair = c("check_unique", "unique", "universal", "minimal"), + rownames = NULL) { + stopifnot(requireNamespace("tibble", quietly = TRUE)) + tibble::as_tibble(as.data.frame(x), ..., .rows = .rows, .name_repair = .name_repair, rownames = rownames) +} + #' @export `[.lints` <- function(x, ...) { attrs <- attributes(x) diff --git a/R/zzz.R b/R/zzz.R index ff5d3ae39..6df487026 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -326,6 +326,9 @@ settings <- NULL ) settings <<- list2env(default_settings, parent = emptyenv()) - invisible() + + if (requireNamespace("tibble", quietly = TRUE)) { + registerS3method("as_tibble", "lints", as_tibble.lints, asNamespace("tibble")) + } } # nocov end diff --git a/tests/testthat/test-methods.R b/tests/testthat/test-methods.R index 10d4b47fc..c73d3a3ee 100644 --- a/tests/testthat/test-methods.R +++ b/tests/testthat/test-methods.R @@ -148,3 +148,11 @@ test_that("within.list is dispatched", { }) expect_identical(vapply(l, `[[`, integer(1L), "line_number"), 2L:3L) }) + +test_that("as_tibble.list is _not_ dispatched directly", { + skip_if_not_installed("tibble") + expect_identical( + nrow(tibble::as_tibble(lint(text = "a = 1", linters = assignment_linter()))), + 1L + ) +})