设置Clojure“常数”在运行时 [英] Setting Clojure "constants" at runtime

查看:114
本文介绍了设置Clojure“常数”在运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Clojure程序,我使用Maven构建为JAR文件。

I have a Clojure program that I build as a JAR file using Maven. Embedded in the JAR Manifest is a build-version number, including the build timestamp.

我可以在运行时使用以下代码从JAR Manifest中轻松地读取这些信息:

I can easily read this at runtime from the JAR Manifest using the following code:

(defn set-version
  "Set the version variable to the build number."
  []
  (def version
    (-> (str "jar:" (-> my.ns.name (.getProtectionDomain)
                                   (.getCodeSource)
                                   (.getLocation))
                    "!/META-INF/MANIFEST.MF")
      (URL.)
      (.openStream)
      (Manifest.)
      (.. getMainAttributes)
      (.getValue "Build-number"))))

defn 内使用 def 是错误的原因。

but I've been told that it is bad karma to use def inside defn.

什么是Clojure惯用的方式来设置常量在运行时?我显然没有build-version信息嵌入我的代码作为 def ,但我想它设置一次(和所有)从 main 函数。

What is the Clojure-idiomatic way to set a constant at runtime? I obviously do not have the build-version information to embed in my code as a def, but I would like it set once (and for all) from the main function when the program starts. It should then be available as a def to the rest of the running code.

UPDATE

UPDATE: BTW, Clojure has to be one of the coolest languages I have come across in quite a while. Kudos to Rich Hickey!

推荐答案

我仍然认为最简单的方法是使用 alter-var-root c> $

I still think the cleanest way is to use alter-var-root in the main method of your application.

(declare version)

(defn -main
  [& args]
  (alter-var-root #'version (constantly (-> ...)))
  (do-stuff))

它在编译时声明Var,值在运行时一次,不需要deref,并且不绑定到主线程。您在上一个问题中没有回应这项建议。您尝试过这种方法吗?

It declares the Var at compile time, sets its root value at runtime once, doesn't require deref and is not bound to the main thread. You didn't respond to this suggestion in your previous question. Did you try this approach?

这篇关于设置Clojure“常数”在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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