Skip to content

Instantly share code, notes, and snippets.

@toomasv
Last active May 4, 2024 07:15
Show Gist options
  • Save toomasv/fd3338a500fdf3e6da49b9d18ffb8c70 to your computer and use it in GitHub Desktop.
Save toomasv/fd3338a500fdf3e6da49b9d18ffb8c70 to your computer and use it in GitHub Desktop.
Transform data into block
make-block: function [data /all /with selection [word! block!]][
if word? selection [selection: to-block selection]
either any [
accessors: select system/catalog/accessors type?/word data
system/words/all [ ; NB! Modifies global "query"
url? data
data: decode-url data
accessors: words-of data
]
system/words/all [
file? data
accessors: [path name suffix modified]
data: object [
path:
name: none
set [path name] split-path data
suffix: suffix? data
modified: system/words/query data
]
]
][
either selection [
if not empty? weird: exclude selection accessors [
cause-error 'user 'message rejoin ["make-block: Unknown accessor" pick [": " "s: "] single? weird weird]
]
][
selection: accessors
]
collect [
foreach sel selection [
if all [keep to set-word! sel]
keep switch/default type?/word d: data/:sel [
word! [to-lit-word d]
path! [to-lit-path d]
][d]
]
]
][
if any [all with][
cause-error 'user 'message rejoin ["make-block: Data of type `" mold type? data "` does not have accessors!"]
]
append copy [] data
]
]
@toomasv
Copy link
Author

toomasv commented May 4, 2024

Usage:

make-block 3x2
;== [3 2]
make-block/all tom@est.ee
;== [user: "tom" host: "est.ee"]
make-block/all url: https://tom@www.est.ee?q=me
;== [scheme: 'https user-info: "tom" host: "www.est.ee" port: none path: none target: none query: "q=...
vars: [query user-info host]
;== [query user-info host]
reduce make-block/with/all url vars    ;Careful -- modifies global query
;== ["q=me" "tom" "www.est.ee"]
reduce vars
;== ["q=me" "tom" "www.est.ee"]
make-block "hi"
;== ["hi"]
to-block "hi"
;== [hi]
make-block %abc/def.red
;== [%abc/ %def.red %.red none]
make-block/all %entities.red
;== [path: %./ name: %entities.red suffix: %.red modified: 19-Dec-2018/21:08:35.815]
>> probe context make-block/all system/build/date()
make object! [
    date: 28-Feb-2024
    year: 2024
    month: 2
    day: 28
    zone: 0:00:00
    time: 21:14:45
    hour: 21
    minute: 14
    second: 45.0
    weekday: 3
    yearday: 59
    timezone: 0:00:00
    week: 9
    isoweek: 9
    julian: 59
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment