我可以引用另一个命名空间,并将其函数公开为当前ns吗? [英] Can I refer another namespace and expose its functions as public for the current ns?

查看:106
本文介绍了我可以引用另一个命名空间,并将其函数公开为当前ns吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为使用会这样做,但似乎在当前命名空间中创建的映射不是公开的。这里是我想要实现的示例:

I thought use would do it but it seems the mapping created in the current namespace is not public. Here is an example of what I'd like to achieve:

(ns my-ns
  (:use [another-ns :only (another-fct)]))

(defn my-fct
  []
  (another-fct 123)) ; this works fine

然后我有另一个命名空间如下:

Then I have another namespace like this:

(ns my-ns-2
   (:require [my-ns :as my]))

(defn my-fct-2
  []
  (my/another-fct 456)) ; this doesn't work



我想这样做,因为 another-ns 是访问数据库的库。我想在一个命名空间( my-ns )中隔离对这个库的所有调用,这样所有的DB依赖函数将被隔离在一个命名空间中,变得更容易切换到另一个数据库,如果需要。

I would like to do that because another-ns is a library to access a database. I would like to isolate all the calls to this library in a single namespace (my-ns), this way all the DB dependent functions would be isolated in a single namespace and it becomes easier to switch to another DB if needed.

这个库的一些功能只是对我很好,但我想增加其他。让我们说读函数很好,但我想用一些验证来增加写函数。

Some of the functions of this library are just fine for me but I'd like to augment others. Let's say the read functions are fine but I'd like to augment the write functions with some validation.

到目前为止,我看到的唯一方法是手动编写所有的映射到 my-ns 甚至对于我不扩充的函数。

The only way I see so far is to hand-code all the mapping into my-ns even for the functions I don't augment.

推荐答案

这有帮助吗?

(defmacro pull [ns vlist]
  `(do ~@(for [i vlist]
           `(def ~i ~(symbol (str ns "/" i))))))

这里有一个例子:

(ns my-ns)

(defmacro pull [ns vlist]
  `(do ~@(for [i vlist]
           `(def ~i ~(symbol (str ns "/" i))))))

(pull clojure.string (reverse replace))

(defn my-reverse
  []
  (reverse "abc"))

(ns my-ns-2)

(defn my-fct-2 []
  (list (my-ns/my-reverse)
        (my-ns/reverse "abc")))

(my-fct-2)

然后:

(defmacro pullall [ns]
  `(do ~@(for [i (map first (ns-publics ns))]
           `(def ~i ~(symbol (str ns "/" i))))))

(pullall clojure.string)

这篇关于我可以引用另一个命名空间,并将其函数公开为当前ns吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆