Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Field constraints #266

Open
trickytank opened this issue Aug 19, 2022 · 0 comments
Open

Field constraints #266

trickytank opened this issue Aug 19, 2022 · 0 comments

Comments

@trickytank
Copy link

trickytank commented Aug 19, 2022

I'd like to find a way to constrain fields, that is, passing tests in a similar way to the Moose Object-oriented system in Perl. This is a suggested enhancement or extension in another package to R6.

What I want to achieve can be done using active fields, though the coding is kind of convoluted and the field value isn't shown in the R6.print method.
An example of this is:

library(R6)
library(checkmate)

CONSTRAINT <- R6Class(
  "CONSTRAINT",
  public = list(

  ),
  private = list(
    x_ = 0
  ),
  active = list(
    x = function(value) {
      if (missing(value)) {
        return(private$x_)
      } else {
        check <- checkmate::checkNumber(value)
        if(is.character(check)) {
          stop("Value attempting to be assigned to x is not valid: ", check)
        }
        value
      }
    }
  )
)

A <- CONSTRAINT$new()
A$x <- 5 # Successful
A$x <- 1L # Successful
A$x <- pi # Successful
A$x <- c(3,5) # Throws an error, as required. 
A$x <- "SD" # Throws an error, as required. 

What I would be hoping for is something like this:

CONSTRAINT_IDEAL <- R6Class(
  "CONSTRAINT",
  public = list(
    x = 0
  ),
  constraints = list(
    x = checkmate::checkNumber # this can be any function that returns TRUE when the field is within the constraints.
  )
)

My main problem is I don't know if this is a possible extension of public/private fields or whether this would have to stick to active bindings (with a rewrite of the R6.print method to show the values of these constrained fields).

I'm willing to have an attempt at developing this myself, though I need to understand much better how R6 works under the hood.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant