constructive icon indicating copy to clipboard operation
constructive copied to clipboard

feature: construct to clipboard

Open JosiahParry opened this issue 2 months ago • 4 comments

I like using constructive to create code to use in tests and I'll need to copy the output of the print method and paste it into another file. I'd suggest having a function construct_clip() that would write the results to the clipboard. An example of an implementation could look like this:

construct_clip <- function(x, ...) {
  rlang::check_installed(
    "clipr",
    "to write to the clipboard"
  )
  res <- constructive::construct(x, ...)
  clipr::write_clip(res$code)
  invisible(res)
}

iris[1:2, ] |> 
  construct_clip()

This makes the following immediately available in my clipboard

data.frame(
  Sepal.Length = c(5.1, 4.9),
  Sepal.Width = c(3.5, 3),
  Petal.Length = c(1.4, 1.4),
  Petal.Width = c(0.2, 0.2),
  Species = factor(c("setosa", "setosa"), levels = c("setosa", "versicolor", "virginica"))
)

JosiahParry avatar Apr 26 '24 14:04 JosiahParry

check out ?constructive_print_mode with the development version :

options(constructive_print_mode = "clipboard")
iris[1:2, ] |> 
  construct()

I considered having a different function or a different arg but an argument is a lot to type every time and with options you can have console and clipboard at the same time for instance with options(constructive_print_mode = c("console", "clipboard")), or construct to script and clipboard a the same time.

moodymudskipper avatar Apr 26 '24 23:04 moodymudskipper

I can confirm that the option worked for me. But I will note that setting the options feels a little odd and I'd personally love an exported function that can achieve this. I often do things with clipr or dput as a one of situation for which setting the option feels like a bit too much work—i.e. its easier to just copy and paste the output than it is to set the option.

JosiahParry avatar Apr 27 '24 11:04 JosiahParry

I understand, another argument for using the option was that I don't want to maintain construct_multi_clip(), construct_reprex_clip()... but I wanted the feature for those as well. Maybe we can have construct_clip() as a simpler wrapper similar to what you suggested, and mention the option there for more niche uses.

moodymudskipper avatar Apr 27 '24 11:04 moodymudskipper

That all sounds good! Perhaps those functions could already serve my need? I think having an example of them in the README could help clarify their use and intent!

JosiahParry avatar Apr 27 '24 11:04 JosiahParry