什么时候应该使用在Clojure中的temporary

什么时候应该使用在Clojure中的temporary

本文介绍了什么时候应该使用在Clojure中的temporary-rebind-a-special-var成语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到一些库,如clojure-twitter使用特殊的vars(用于动态绑定的那些由星号包围)用于oauth身份验证。您将验证保存在var中,然后使用(with-oauth myauth ..)。我认为这是一个很好的解决这类问题,因为你可以重新绑定 auth var应用程序的每个用户。

I've noticed that some libraries such as clojure-twitter use special vars (the ones intended for dynamic binding that are surrounded by asterisks) for oauth authentication. You save your authentication in a var and then use (with-oauth myauth ..). I think this is a very nice solution to this sort of problem, because you can rebind the auth var for each user of the application.

我在我写的电子邮件客户端中采取了类似的路线。我有一个特殊的变量名为 session ,我绑定到一个地图与当前用户的会话和用户信息,有各种重要的函数,使用信息从var。我写了一个宏,使用会话临时重新绑定在一组表单的上下文中传递给会话。原来是一个相当干净的解决方案(对我)。

I've taken a similar route in an email client I've been writing. I have a special var named session that I bind to a map with the current user's session, and user info, and there are various important functions that use information from that var. I wrote a macro, with-session to temporarily rebind it in the context of a set of forms passed to with-session. It turns out to be a pretty clean solution (to me).

所以,我的问题是这样:我'doin'it rite'?这是一个糟糕的设计决定,还是这是特殊变量的预期用途之一?

So, my question is this: am I 'doin' it rite'? Is this a bad design decision, or is this one of the intended usages of special vars?

推荐答案

你似乎在做非常正确。实际上,有一些内置/ contrib宏工作类似, with -out-str clojure.contrib.sql / with -connection 。后者是当今Clojure基础设施中相当重要的一部分,因此它使用的任何习语都经过很多人的审查。

You seem to be doing it exactly right. In fact, there's a number of built-in / contrib macros which work similarly, say with-out-str or clojure.contrib.sql/with-connection. The latter is a rather key part of present day Clojure infrastructure, so whatever idioms it uses have been scrutinised by a lot of people.

要记住的重要的事情是在绑定 / 与绑定范围内启动的线程继承所讨论的var的回弹值;相反,他们看到根绑定。如果你想将你的绑定传播到工作者线程/代理,可以显式地传递它们(作为函数参数),或者使用 bound-fn

The important gotcha to keep in mind is that threads you launch while in scope of a bindings / with-bindings form do not inherit the rebound values for the vars in question; rather, they see the root bindings. If you want to propagate your bindings to worker threads / agents, either pass them on explicitly (as function arguments, say) or use bound-fn.

这篇关于什么时候应该使用在Clojure中的temporary-rebind-a-special-var成语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 06:09