Relative environmental sending protocols / multimethods to clojure

I ran into a problem in how architecture represents a certain part of my software. Suppose I have a function called make-temp-dir (and many others) that does some dark magic depending on the current OS. I want implementations of these methods for each OS in a separate namespace.

Firstly, I believe that protocols (if possible) or multimethods are the solution to this. However, I have never seen an example of their use with implementations spanning multiple namespaces. And I can’t understand how this works out.

Secondly, if I use protocols for this, I will have to call the methods something like

 (make-temp-dir current-os arg-1 arg-2) 

Somehow, passing os as the first argument all the time doesn't look too good for me. For semantic sake, I would like make-temp-dir to make-temp-dir smart decisions depending on the OS. Of course, I can use some macros and do something like

 (doto current-os (make-temp-dir arg-1 arg2)) 

but it seems wrong.

How to do it? Or am I going wrong? Any help was appreciated.

Change Ok, thanks a ton @kotarak, I managed to do something. For those who stumbled upon this, https://gist.github.com/2477120 . His work is beautiful, I think I will go with it. Thanks to everyone.

+6
source share
2 answers
 (ns your.utils) (def current-os) (defmulti make-temp-dir (fn [& _] current-os)) (ns your.utils.mac) (defmethod make-temp-dir :mac-os-x [ab] (...)) (ns your.utils.win) (defmethod make-temp-dir :windows [ab] (...)) 

In the startup code, you must initialize current-os with alter-var-root before using any of the utility functions.

 (let [os (find-os)] (alter-var-root #'current-os (constantly os)) (require (case os :mac-os-x 'your.utils.mac :windows 'your.utils.win))) 

Hope you get started.

+7
source

I can't say for sure, but it looks like you can invent the wheel that Java provides. Try https://github.com/Raynes/fs for a convenient shell for some of what Java provides in addition to the basic tools in clojure.java.io ( http://clojuredocs.org/clojure_core/clojure.java.io ).

You can also find https://github.com/drakerlabs/milieu if your question goes beyond OS-specific branching to configuration values ​​for a particular environment. I wrote this code as part of our proprietary projects here at Draker, and we recently released it as freeware. We have not yet officially announced this community, but it is located in Klozhary and is ready for use. Feedback is welcome! The concept that stimulated its creation was an environment in the sense of dev / test / staging / production, etc., but I see no reason why it could not be used to configure variables for different operating systems.

+1
source

Source: https://habr.com/ru/post/913953/


All Articles