Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # wrap a function into a command object
- register <- function(name, operation) {
- proto(
- name = name,
- func = operation,
- perform = function(., ...) {
- func <- with(., func) # unwrap bound proto method
- do.call(func, list(), envir=environment(operation))
- }
- )
- }
- # dynamic invocation test outside of proto
- do_call_test <- function(operation) {
- do.call(operation, list(), envir=environment(operation))
- }
- context('proto with functions as data')
- test_that("cmd execution", {
- # This varible should be visible inside op
- command_result <- 100
- op <- function() {
- # Utility to list all variables in an environment
- # Modified from Matloff, Norman. The Art of R Programming
- show.frame <- function(upn) {
- # determine the proper environment
- if (upn < 0) {
- env <- .GlobalEnv
- } else {
- env <- parent.frame(n=upn+1)
- }
- cat('\nShowing frame', upn, 'with the following environment\n')
- print(env)
- cat('Variables:\n')
- # get the list of variable names
- vars <- ls(envir=env)
- # for each variable name, print its value
- for (vr in vars) {
- vrg <- get(vr,envir=env)
- if (!is.function(vrg)) {
- cat(vr,":\n",sep="")
- print(vrg)
- }
- }
- }
- for (n in c(0, 1, 2)) {
- cat("\nFrame", n, "\n")
- show.frame(n)
- }
- command_result
- }
- cat('\n\nCurrent environment\n')
- print(environment())
- cat("\n---- Calling op directly\n")
- expect_equal(op(), command_result)
- cat("\n---- Calling op with do.call\n")
- expect_equal(do_call_test(op), command_result)
- cat("\n---- Calling op with do.call inside proto\n")
- cmd <- register('cmd', op)
- expect_equal(cmd$perform(), command_result)
- })
Add Comment
Please, Sign In to add comment