Skip to content

Instantly share code, notes, and snippets.

@alexfaber2011
Created January 13, 2016 20:17
Show Gist options
  • Save alexfaber2011/2f163aef0f6e96439f48 to your computer and use it in GitHub Desktop.
Save alexfaber2011/2f163aef0f6e96439f48 to your computer and use it in GitHub Desktop.
Using `with-redefs` to redef a function that's called inside a go block
; ---------------------------------------------------------------------------------
; handler code
; ---------------------------------------------------------------------------------
; My handler code fetches messages in parrallel and then picks them off of the channel
; vector within the go block. I've succesfully redef'ed `http/get` by bringing it out
; of the `go` block, but redef'ing 're-frame/dispatch` doesn't seem to be working.
(defn fetch-full-messages [db [scenario-name]]
(if-let [scenario (get-in db [:admin-configuration :scenarios scenario-name])]
(letfn [(fetch-full-message-by-id [message-id]
(http/get (str (form-full-base-url db) "Messages/" message-id) {:with-credentials? false :basic-auth (form-credentials-map db)}))]
(let [message-ids (map #(get-in % [:body :messageId]) (:messages scenario))
channels (mapv fetch-full-message-by-id message-ids)]
(go
(let [responses (loop [responses [] ; definitely could refactor this into a reduce (I was a less
remaining-channels channels] ; seasoned clojurescript developer when I wrote this)
(if (empty? remaining-channels)
responses
(recur (conj responses (<! (first remaining-channels))) (vec (rest remaining-channels)))))]
(if (every? has-success-status? responses)
(do
(re-frame/dispatch [:save-fetched-messages responses])
(re-frame/dispatch [:form-broadcast-instructions]))
(js/alert "Error: Unsuccessful fetch of at least one message in scenario. Not able to proceed"))))))
(nav/set-location! "/"))
db)
; ---------------------------------------------------------------------------------
; test
; ---------------------------------------------------------------------------------
; Not a proper test ofcourse since I'm not asserting anything, but I'm trying to
; figure out why my `re-frame/dispatch` redef is not working.
(deftest temp-test
(cljs.test/async done
(with-redefs [http/get (fn [url]
(let [chan (chan)]
(async/put! chan {:status 200 :url url})
chan))
re-frame/dispatch (fn [] (print "dispatching now"))]
(handler/fetch-full-messages @db ["test"])
(done))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment