Skip to content

Commit

Permalink
V2 no errors.
Browse files Browse the repository at this point in the history
  • Loading branch information
dereckmezquita committed Jul 27, 2024
1 parent 1f34162 commit 615b152
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions dev/s3-assignment-method/s3-assignment-method-v2.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Define the S3 class constructor
MyS3Class <- function(value) {
structure(list(value = value), class = "MyS3Class")
}

# Define print method for MyS3Class
print.MyS3Class <- function(x, ...) {
cat("MyS3Class object with value:", x$value, "\n")
}

# Create an active binding function
create_active_binding <- function(name, initial_value) {
value <- initial_value

# Remove existing binding if it exists
if (exists(name, envir = .GlobalEnv)) {
rm(list = name, envir = .GlobalEnv)
}

makeActiveBinding(
name,
function(v) {
if (missing(v)) {
return(value)
} else {
cat("hello\n")
value <<- MyS3Class(v)
}
},
.GlobalEnv
)
}

# Create an object of MyS3Class
obj <- MyS3Class(10)

# Create an active binding for the object
create_active_binding("obj", obj)

# Access the value
print(obj) # Should print 10

# Assign a new value and trigger the custom logic
obj <- 29 # Should print "hello"
print(obj) # Should print 29

0 comments on commit 615b152

Please sign in to comment.