Guest User

Untitled

a guest
Oct 21st, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. # wrap a function into a command object
  2. register <- function(name, operation) {
  3. proto(
  4. name = name,
  5. func = operation,
  6. perform = function(., ...) {
  7. func <- with(., func) # unwrap bound proto method
  8. do.call(func, list(), envir=environment(operation))
  9. }
  10. )
  11. }
  12.  
  13. # dynamic invocation test outside of proto
  14. do_call_test <- function(operation) {
  15. do.call(operation, list(), envir=environment(operation))
  16. }
  17.  
  18. context('proto with functions as data')
  19.  
  20. test_that("cmd execution", {
  21.  
  22. # This varible should be visible inside op
  23. command_result <- 100
  24.  
  25. op <- function() {
  26.  
  27. # Utility to list all variables in an environment
  28. # Modified from Matloff, Norman. The Art of R Programming
  29. show.frame <- function(upn) {
  30. # determine the proper environment
  31. if (upn < 0) {
  32. env <- .GlobalEnv
  33. } else {
  34. env <- parent.frame(n=upn+1)
  35. }
  36. cat('\nShowing frame', upn, 'with the following environment\n')
  37. print(env)
  38. cat('Variables:\n')
  39. # get the list of variable names
  40. vars <- ls(envir=env)
  41. # for each variable name, print its value
  42. for (vr in vars) {
  43. vrg <- get(vr,envir=env)
  44. if (!is.function(vrg)) {
  45. cat(vr,":\n",sep="")
  46. print(vrg)
  47. }
  48. }
  49. }
  50.  
  51. for (n in c(0, 1, 2)) {
  52. cat("\nFrame", n, "\n")
  53. show.frame(n)
  54. }
  55.  
  56. command_result
  57. }
  58.  
  59. cat('\n\nCurrent environment\n')
  60. print(environment())
  61.  
  62. cat("\n---- Calling op directly\n")
  63. expect_equal(op(), command_result)
  64.  
  65. cat("\n---- Calling op with do.call\n")
  66. expect_equal(do_call_test(op), command_result)
  67.  
  68. cat("\n---- Calling op with do.call inside proto\n")
  69. cmd <- register('cmd', op)
  70. expect_equal(cmd$perform(), command_result)
  71. })
Add Comment
Please, Sign In to add comment