On Thu, Mar 1, 2012 at 8:33 PM, Cymen Vig <[email protected]> wrote:
> I attempted to do something like this:
>
> (ns parent)
> (defmulti my-method (fn [x] (:method x))
>
> (ns child1)
> (defmethod my-method :zzz
> ...)
>
> (ns child2)
> (defmethod my-method :aaa
> ...)
>
> However the problem is the children need to use the parent namespace in
> order to have the method definition and the code that uses all of this needs
> to use all the namespaces too. This creates a circular reference and
> compilation fails.
I will not in any way claim to know how or why this works. I'm just
starting to use multimethods myself, but I'll give you my set up that
appears to be working at the moment.
I have a namespace:
(ns store.store)
(defmulti serialize method)
(defmulti slurp method)
in store.clj
I have 1 implementation:
(ns store.file-system
[:use [store.store]]
…)
(def base "")
(defmethod serialize :file-system [_ file-name contents]
(fs-utils/write-to contents (str base "/" file-name)))
(defmethod slurp :file-system [_ file-name]
(clojure.core/slurp (str base "/" file-name)))
I then use this from another namespace, requiring store.store and
store.store.file-system:
(ns library
[:require [wallpaper-manager-core.store.file-system :as
store-file-system]]
[:require [wallpaper-manager-core.store.store :as store]])
(binding [store-file-system/base (fs/home)]
(def library (ref (read-library) :validator library-validator)))
(defn serialize-library [library]
(store/serialize :file-system "library.clj" library))
And this all seems to work fine for me. Maybe someone else can explain
why it does for me and doesn't for you. Maybe it has something to do
with `use` vs. `require`?
> 1) Is it a bad idea to try to put the defmulti and defmethods into separate
> namespaces?
I don't personally see it as a bad idea, simply because I see defmulti
as a nice, clean way of defining an Interface with multiple
implementations to choose from. One of the ways that I'm using it it
to implement my html vs. json routes. I'm hoping that I can have a
route1.json namespace for all of the json requests and route1.html for
all the html requests. Based on my success with the store namespace I
don't foresee this being a problem, but maybe it will.
I heavily edited the code to remove uninteresting bits and I didn't
test it so be aware of that. :)
Hope that helps!
--
In Christ,
Timmy V.
http://blog.twonegatives.com/
http://five.sentenc.es/ -- Spend less time on mail
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en