Search code examples
rroxygen2r6

How to correctly document R6 self


I have a function built with an R6class and was wondering the best way to pass devtools::check() is. Currently this repex gives the note

> checking R code for possible problems ... NOTE
  obj_gen : <anonymous>: no visible binding for global variable ‘self’
  Undefined global functions or variables:
    self

It only gives the note, however, when self is actually called. Ie in the print function, but not in the assignment inside initialise.

In the Tidyverse (here), importFrom R6 R6Class is used. In this case however the calling of self in the print function seems to trigger the global variables note.

Repex

#' func
#' @param ... opts
#' @examples
#'\dontrun{
#' obj_gen(bar = "fubar")
#'}
obj_gen <- function(...){

  #' @importFrom R6 R6Class
  obj <- R6::R6Class("my_class",
              public = list(
                foo = NULL,
                initialize = function(bar = NA){
                  self$foo <- bar
                },
                print = function(){
                  cat("Anyone for ",
                      self$foo,
                      "?",
                      sep = "")
                }
              )
  )
  obj$new(...)
}

A collegue very helpfully suggested adding it to globalVariables(info) which I am considering. Id like to know if there is a better way to deal with it, using documentation, however :)

My Roxygen version is 7.1.1.


Solution

  • Solution with a dummy self <- NA definition.

    #' func
    #' @param ... opts
    #' @import R6
    #' @examples
    #'\dontrun{
    #' obj_gen(bar = "fubar")
    #'}
    obj_gen <- function(...){
      self <- NA
      obj <- R6Class("my_class",
                         public = list(
                           foo = NULL,
                           initialize = function(bar = NA) {
                             self$foo <- bar
                           },
                           print = function() {
                             cat("Anyone for ",
                                 self$foo,
                                 "?",
                                 sep = "")
                           }
                         )
      )
      obj$new(...)
    }