Skip to content

Method dispatch for rx_string #11

@dmi3kno

Description

@dmi3kno

Basically boils down to detecting that .data is not of rx_string class and acting as though first argument is the value argument.
Reference: http://adv-r.had.co.nz/S3.html

UPDATED: sanitize now has method dispatch, so we can simply write

## unexported function for sanitizing arguments
sanitize_args <- function(...){
   if (missing(...)) return(NULL) 
  res <- sapply(list(...), sanitize) 
  Reduce(paste0, res)
}

is.rx_string <- function(x){
  inherits(x, "rx_string")
}

# class constructor - also unexported function. 
rx <- function(x){
  if(is.rx_string(x)) return(x)
  class(x) <- c("rx_string", class(x)) 
  x
}

rx_literal <- function(.data, ...) {
  UseMethod("rx_literal", .data)
}

rx_literal.character <- function(.data, ...){
  res <- paste0(sanitize(.data), sanitize_args(...))
  rx(res)
}

rx_literal.rx_string <- function(.data, ...) {
  res <- paste0(.data, sanitize_args(...))
  rx(res)
}

Now you dont need a constructor. Function works both in chain and stand alone

rx_literal("?@")
#> [1] "\\?@"
#> attr(,"class")
#> [1] "rx_string" "character"

rx_literal("?") %>% rx_literal("@")
#> [1] "\\?@"
#> attr(,"class")
#> [1] "rx_string" "character"

Hadley says we should also implement a few essential methods. We should rethink all of our functions with vectorization in mind.

When implementing a vector class, you should implement these methods: length, [, [<-, [[, [[<-, c. (If [ is implemented rev, head, and tail should all work).

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions