1

I have a ReferenceClass in R.

How can I add a method "print()" to it, which will print the values of all of the fields in the class?

Contango
  • 76,540
  • 58
  • 260
  • 305

2 Answers2

3

Perhaps a better implementation is the following

Config = setRefClass("Config",
  fields = list(    
    ConfigBool = "logical", 
    ConfigString = "character"),
  methods = list(
    ## Allow ... and callSuper for proper initialization by subclasses
    initialize = function(...) {
        callSuper(..., ConfigBool=TRUE, ConfigString="A configuration string")
        ## alterantive:
        ##    callSuper(...)
        ##    initFields(ConfigBool=TRUE, ConfigString="A configuration string")
    },
    ## Implement 'show' method for automatic display
    show = function() {
        flds <- getRefClass()$fields()
        cat("* Fields\n")
        for (fld in names(flds))  # iterate over flds, rather than index of flds
            cat('  ', fld,': ', .self[[fld]], '\n', sep="")
    })
  )

The following illustrates use of the Config constructor (no need to invoke 'new') and automatic invocation of 'show'

> Config()
* Fields
  ConfigBool: TRUE
  ConfigString: A configuration string
Contango
  • 76,540
  • 58
  • 260
  • 305
Martin Morgan
  • 45,935
  • 7
  • 84
  • 112
  • Nice answer, definitely better than mine. I'm marking it as the official answer. – Contango May 05 '14 at 16:24
  • For the record, `show()` is called by default, so `Config()` is equivalent to `Config()$show()`. – Contango May 05 '14 at 16:28
  • And for the record, to suppress the "No visible binding" messages that are generated when sourcing this function, see http://stackoverflow.com/questions/23475309/in-r-is-it-possible-to-suppress-note-no-visible-binding-for-global-variable. – Contango May 05 '14 at 16:32
2

Run the following demo in an R console:

# Reference Class to store configuration

Config <- setRefClass("Config",
  fields = list(    
    ConfigBool = "logical", 
    ConfigString = "character"
    ),
    methods = list(
        # Constructor.
        initialize = function(x) {
            ConfigBool <<- TRUE
            ConfigString <<- "A configuration string"
        },
        # Print the values of all of the fields used in this class.
        print = function(values) {
            cat("* Fields\n")
            fieldList <- names(.refClassDef@fieldClasses)           
            for(fi in fieldList)
            {
                variableName = fi
                variableValue = field(fi)
                cat('  ',variableName,': ',variableValue,'\n',sep="")           
            }
        }
  )
)

config <- Config$new()
config
config$print()

---test code---

# Demos how to print the fields of the class using built-in default "show()" function.
> config$show()
Reference class object of class "Config"
Field "ConfigBool":
[1] TRUE
Field "ConfigString":
[1] "A configuration string"

# Omitting the "show()" function has the same result, as show() is called by default.
> config
Reference class object of class "Config"
Field "ConfigBool":
[1] TRUE
Field "ConfigString":
[1] "A configuration string"

# Demos how to print the fields of the class using our own custom "print" function.
> config$print()
* Fields
  ConfigBool: TRUE
  ConfigString: A configuration string

In addition, typing the following shows the source code for the default "show" function that is included with all ReferenceClasses:

config$show
Contango
  • 76,540
  • 58
  • 260
  • 305
  • 3
    Reference classes have a `show` method. Defining a new show method will enable printing using that `show` method when you issue `> config` – jdharrison May 04 '14 at 15:01
  • @jdharrison Thanks, I had just discovered this when you posted your comment; I've updated the answer to reflect this. – Contango May 04 '14 at 15:05
  • 1
    Don't bother with `Print`, just implement `methods(list(show=function() {...}))`; don't explicitly call config$show(), just type `config`. – Martin Morgan May 04 '14 at 15:18
  • And for the record, to suppress the "No visible binding" messages that are generated when sourcing this function, see http://stackoverflow.com/questions/23475309/in-r-is-it-possible-to-suppress-note-no-visible-binding-for-global-variable. – Contango May 05 '14 at 16:32