Back

Coercions (clj)

(source)

protocol

Coerce between various 'resource-namish' things.

Examples

jonase/eastwood
(ns testcases.unusednss3
  (:require [clojure.core.protocols :as protocols]
            [clojure.core.reducers  :as reducers]
            [clojure.data           :as data]
            [clojure.java.io        :as io]
            [clojure.reflect        :as reflect]))

(deftype Foo [whatever]
  io/Coercions
  (as-file [x] nil)
  (as-url  [x] nil))
clojure-emacs/refactor-nrepl
(ns refactor-nrepl.fs-test
  (:require
   [clojure.java.io :as io]
   [clojure.test :refer [deftest is]])
  (:import
   (java.io File)))

(deftest extensions-are-disabled
  (is (try
        (-> "project.clj" File. .toPath io/file)
        false
        (catch Exception e
          (assert (-> e
                      .getMessage
                      #{"No implementation of method: :as-file of protocol: #'clojure.java.io/Coercions found for class: sun.nio.fs.UnixPath"}))
          true))))
Otann/wrench
(ns wrench.core-test
  (:require [clojure.test :refer :all]
            [clojure.spec.alpha :as s]
            [clojure.java.io :as io]
            [clojure.tools.namespace.repl :as ns-tools]
            [wrench.core :as cfg]))


(deftest coercion
  (testing "Coercions work and are idempotent"
    (are [?in ?spec ?out]
      (do (is (= ?out (#'cfg/coerce ?in ?spec)))
          (is (= ?out (#'cfg/coerce ?out ?spec))))
reborg/clojure-essential-reference
(require '[clojure.java.io :as io])

(keys (:impls io/Coercions))        ; <1>
;; (nil java.lang.String java.io.File java.net.URL java.net.URI)
reborg/clojure-essential-reference
(require '[clojure.java.io :as io])
(import '[java.nio.file Path FileSystems])

(extend-protocol io/Coercions ; <1>
  Path
  (as-file [path] (io/file (.toUri path)))
  (as-url [path] (io/as-url (.toUri path))))