clojureclojure-java-interopedn

How do I pass custom parameter to edn reader?


I following clojure code

(defn reverse-reader [coll]
    (assert (coll? coll) "you can only reverse collections")
    (reverse coll)
)

(def custom-readers {'demo/reverse reverse-reader})

(defn getContent
    [filename myCustomObject]
    (edn/read-string
        {:readers custom-readers}
        (slurp filename))
)

I am passing following EDN file

{
    :a 1
    :b [1 2 3 4 5]
    :c #demo/reverse [5 4 3 2 1]
}

My question is: When I call (getContent "ednfilepath" myCustomObject), reverse-reader gets called with collection defined in EDN... how can I pass myCustomObject from getContent to function reverse-reader ?

Thanks for help in advance.


Solution

  • Based on your comment it looks like you want to add a parameter to reverse-reader and create a new function as the tag reader in getContent:

    (defn reverse-reader [coll custom]
      ...)
    
    (defn get-custom-readers [custom]
      {'demo/reverse (fn [c] (reverse-reader c custom))})
    
    (defn getContent
        [filename myCustomObject]
        (edn/read-string
            {:readers (get-custom-readers myCustomObject])
            (slurp filename)))