Skip to content

Commit 4ea5e35

Browse files
committed
assign to hidden env and attach to globalenv
1 parent 89c070d commit 4ea5e35

File tree

3 files changed

+27
-18
lines changed

3 files changed

+27
-18
lines changed

NAMESPACE

-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
11
export("set_string_ops")
22
export("string_concat_op")
33
export("string_format_op")
4-
export("concat_op")
5-
export("format_op")

R/stringplus_functions.R

+26-15
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,35 @@
1-
concat_op <- ""
2-
format_op <- ""
3-
41
allowed_ops <- c("$", "@", "^", "*", "/", "-", "+", "&", "|", "&&", "||")
52

63
set_string_ops_session <- function(concat = "&", format = "|") {
7-
# ns <- getNamespace("base")
4+
5+
# trying to assign in namespace doesn't work
6+
# ns <- getNamespace("stringplus")
87
# rlang::env_unlock(ns)
9-
# unlockBinding(concat, ns)
10-
# unlockBinding(format, ns)
11-
assign(concat, string_concat_op, envir = globalenv(), inherits=FALSE)
12-
assign(format, string_format_op, envir = globalenv(), inherits=FALSE)
8+
# clear_string_ops(ns)
9+
# assign(concat, string_concat_op, envir = ns, inherits=FALSE)
10+
# assign(format, string_format_op, envir = ns, inherits=FALSE)
11+
# namespaceExport(ns, concat)
12+
# namespaceExport(ns, format)
1313
# rlang::env_lock(ns)
1414

15-
ns <- getNamespace("stringplus")
16-
rlang::env_unlock(ns)
17-
unlockBinding("concat_op", ns)
18-
unlockBinding("format_op", ns)
19-
assign("concat_op", concat, envir = ns, inherits=FALSE)
20-
assign("format_op", format, envir = ns, inherits=FALSE)
21-
rlang::env_lock(ns)
15+
# assigning ops to globalenv directly makes it risky as its easy to accidentally remove them
16+
# e.g. via rm(list=ls())
17+
# Instead assign to custom env and attach it to globalenv as a hidden environment
18+
19+
# first check if already assigned and remove it
20+
if(".stringplus" %in% search()) {
21+
detach(".stringplus", character.only=TRUE)
22+
}
23+
env <- new.env(parent = globalenv())
24+
environment(string_concat_op) <- env
25+
assign(concat, string_concat_op, envir = env, inherits=FALSE)
26+
environment(string_format_op) <- env
27+
assign(format, string_format_op, envir = env, inherits=FALSE)
28+
assign("concat_op", concat, envir = env, inherits=FALSE)
29+
assign("format_op", format, envir = env, inherits=FALSE)
30+
31+
assign(".stringplus", env, envir = globalenv())
32+
attach(get(".stringplus", envir = globalenv()), pos = 2, name = ".stringplus", warn.conflicts=FALSE)
2233
}
2334

2435
store_string_ops <- function(concat = "&", format = "|") {

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
# stringplus
44

5-
Combine strings using builtin infix for convenience.
5+
Combine strings using builtin infix operators.
66

77
### Install
88
```

0 commit comments

Comments
 (0)