title: Using a function constructor to add methods to a reference class
body: <p>I'm trying to simplify the process of creating and submitting queries to the Google Analytics API through <a href="https://github.com/skardhamar/rga" rel="nofollow">skardhamar's rga</a>. I'm leading a small analytics team which creates reports for clients, and my coworkers are much less comfortable working with scripts and R. As such, I'm trying to provide a few foundational elements and a report template to reduce complexity.</p>
  
  <p>We often run comparisons between sites, so I've created a profile-specific reference class which contains things like the account ID, profile ID, etc. It will come with a small set of predefined query methods, such as the following:</p>
  
  <pre><code>profile &lt;- setRefClass("profile",
                         fields = list(
                           accountID = "character",
                           profileID = "character"),
                         methods = list(
                           topPages = function() {
                             ga$getData(profileID,
                                        start.date = helper$start,
                                        end.date = helper$end,
                                        metrics = "ga:pageviews,ga:bounceRate",
                                        dimensions = "ga:pagePath",
                                        sort = "-ga:pageviews")
                           })
                         )
  </code></pre>
  
  <p>I may end up adding a field to store API returns into to limit the number of unnecessary API calls we're making, but that's neither here nor there.</p>
  
  <p>To construct these profile objects, and to add new methods to their reference class, I have a helper reference class:</p>
  
  <pre><code>helper &lt;- setRefClass("helper",
                        fields = list(
                          start = "character",
                          end = "character"),
                        methods = list(
                          newMethod = function(name="", metrics="", dimensions="",
                                               sort="") {
                            **take the passed arguments and construct a new 
                            query function**
                            **add function to the profile reference class**
                          },
                          newProfile = function(account="", profile="", name="") {
                            **search for matching account and profile**
                            **create new profile-class object with the passed name**
                          })
                        )
  </code></pre>
  
  <p>Ignoring the potential problems in how I've ordered these examples, is the <code>helper$newMethod()</code> I've described even possible?</p>