From d7f3a2042308ada08d4504ad1d6c2f82177dd815 Mon Sep 17 00:00:00 2001 From: Cam Saul <1455846+camsaul@users.noreply.github.com> Date: Tue, 3 Jan 2023 18:37:14 -0800 Subject: [PATCH] Fix `merge` for an Instance (workaround for https://github.com/clj-commons/potemkin/issues/70) (#46) --- .dir-locals.el | 1 + src/toucan2/instance.clj | 16 ++++++++++++++++ src/toucan2/magic_map.clj | 2 +- test/toucan2/instance_test.clj | 7 +++++++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/.dir-locals.el b/.dir-locals.el index 900a8a9..ba143a9 100644 --- a/.dir-locals.el +++ b/.dir-locals.el @@ -9,5 +9,6 @@ (eval . (put 'p/def-map-type 'clojure-doc-string-elt 2)) (eval . (put-clojure-indent 'p/defprotocol+ '(1 (:defn)))) (eval . (put-clojure-indent 'p/def-map-type '(2 nil nil (:defn)))) + (eval . (put-clojure-indent 'p/deftype+ '(2 nil nil (:defn)))) (eval . (put-clojure-indent 'with-meta '(:form))) (eval . (put-clojure-indent 'with-bindings* '(:form)))))) diff --git a/src/toucan2/instance.clj b/src/toucan2/instance.clj index 9c03798..a262f7b 100644 --- a/src/toucan2/instance.clj +++ b/src/toucan2/instance.clj @@ -67,6 +67,22 @@ (Instance. model orig m new-meta))) clojure.lang.IPersistentCollection + (cons [this o] + (cond + (map? o) + (reduce #(apply assoc %1 %2) this o) + + (clojure.core/instance? java.util.Map o) + (reduce + #(apply assoc %1 %2) + this + (into {} o)) + + :else + (if-let [[k v] (seq o)] + (assoc this k v) + this))) + (equiv [_this another] (cond (clojure.core/instance? toucan2.protocols.IModel another) diff --git a/src/toucan2/magic_map.clj b/src/toucan2/magic_map.clj index d7d7db3..8adcdd1 100644 --- a/src/toucan2/magic_map.clj +++ b/src/toucan2/magic_map.clj @@ -30,7 +30,7 @@ "The default magic map transform function. Converts things to `kebab-case`, preserving namespaces." [k] (when k - (if (and (clojure.core/instance? clojure.lang.Named k) (namespace k)) + (if (and (instance? clojure.lang.Named k) (namespace k)) (keyword (->kebab-case (namespace k)) (->kebab-case (name k))) (keyword (->kebab-case (name k)))))) diff --git a/test/toucan2/instance_test.clj b/test/toucan2/instance_test.clj index f2d3847..c6da039 100644 --- a/test/toucan2/instance_test.clj +++ b/test/toucan2/instance_test.clj @@ -411,3 +411,10 @@ empty-instance)) (is (instance/instance? empty-instance)) (is (instance/instance-of? ::venues empty-instance)))))) + +(deftest ^:parallel merge-test + (let [m (instance/instance ::birds {:name "Parroty"})] + (are [m2 expected] (= expected + (merge m m2)) + {:type :parakeet} {:name "Parroty", :type :parakeet} + nil {:name "Parroty"})))