Skip to content

Instantly share code, notes, and snippets.

@janherich
Last active January 4, 2016 08:19
Show Gist options
  • Save janherich/8594342 to your computer and use it in GitHub Desktop.
Save janherich/8594342 to your computer and use it in GitHub Desktop.
polymorphic finder
(require '[clojure.set :as set])
(require '[clojure.java.jdbc :as j])
(def mysql-db {:subprotocol "mysql"
:subname "//127.0.0.1:3306/clojure_test"
:user "clojure_test"
:password "clojure_test"})
(defn product-service [key]
(println (str "Finding product with key: " key))
(j/query mysql-db ["select * from product where id = ?" key]))
(defn individual-plan-service [key]
(println (str "Finding individual plan with key: " key))
(j/query mysql-db ["select * from individual_plan where id = ?" key]))
(defn team-plan-service [key]
(println (str "Finding team plan with key: " key))
(j/query mysql-db ["select * from team_plan where id = ?" key]))
(defn section-service [key]
(println (str "Finding section with key: " key))
(j/query mysql-db ["select * from section where id = ?" key]))
(defn not-found []
(println "Nothing to dispatch")
;; define dispatch map
(def dispatch-map {#{:product-id :screencast-id :book-id :show-id} product-service
#{:individual-plan-id} individual-plan-service
#{:team-plan-id} team-plan-service
#{:section-id} section-service})
(defn- get-dispatch-entry [params dispatch-map]
(first (filter (fn [[k v]] (seq (set/intersection k params))) dispatch-map)))
(defn requested-purchaseable
"Takes dispatch map, set of params from request and no-arg function to be called
when no dispatch value is found"
[dispatch-map params not-found-fn]
(let [params-keys (set (keys params))]
(if-let [[dispatch-params service-fn] (get-dispatch-entry params-keys dispatch-map)]
(service-fn (get params (first (set/intersection dispatch-params params-keys))))
(not-found-fn))))
;; test various dispatches
(requested-purchaseable dispatch-map {:product-id 10} not-found)
(requested-purchaseable dispatch-map {:book-id 11} not-found)
(requested-purchaseable dispatch-map {:individual-plan-id 12} not-found)
(requested-purchaseable dispatch-map {:team-plan-id 13} not-found)
(requested-purchaseable dispatch-map {:section-id 14} not-found)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment