klmr / box

Write reusable, composable and modular R code
https://klmr.me/box/
MIT License
833 stars 47 forks source link

Import as syntax `alias` #276

Closed dereckmezquita closed 2 years ago

dereckmezquita commented 2 years ago

Hello not sure if I missed the documentation or if it's not an available feature but I would like to have something like an import as feature for getting specific objects from a module, in TypeScript I can do:

import { SimpleTime as st } from './utils/SimpleTime';

// st is now the alias for the object pulled from the module which was previously named SimpleTime

I tried the alias argument in box but it just sets the results of the module to a variable name; I will try to illustrate with code:

Module code:

#' @export
SimpleTime <- R6::R6Class(
    "SimpleTime",
    public = list(
        start = NULL,
        initialize = \() {
            self$start <- Sys.time()
        },

        elapsed = \() {
            return(as.numeric(Sys.time() - self$start))
        }
    )
)

Different imports and expected results:

box::use(./utils/SimpleTime)

# can now use the following
ls()
# [1] "SimpleTime"

SimpleTime$SimpleTime$new()

Now I found this syntax to simplify it and import SimpleTime directly (I would like to do this but with an alias):

box::use(./utils/SimpleTime[ SimpleTime ])

ls()
# character(0)

SimpleTime$new()

Then I tried this:

box::use(st = ./utils/SimpleTime[ SimpleTime ])

ls()
# [1] "st"

# I can use the import as
st$SimpleTime$new()

My expected result is to be able to use it as such directly:

st$new()

Is there a way to do this that I missed or could this be an added feature? If it doesn't exist may I suggest the syntax:

box::use(st = ./utils/SimpleTime[ SimpleTime as st ])

st$new()
dereckmezquita commented 2 years ago

Found it:

box::use(./utils/SimpleTime[ st = SimpleTime ])