Zope

TAL が便利だから何でもかんでも TAL でやってる。
特にHTMLレンダラみたいなウザくてタルい作業は TAL しか使ってない気味。ヤバげ。
そんな中で勢いで書いた、インターフェースを文字列で指定してインターフェースが実装されてればそのままのオブジェクトで、アダプタがあればアダプトして、なんも指定されてなければ None 返すパスアダプタ。

  • implements.py
from zope.app.traversing.interfaces import IPathAdapter

class TalesInterfaceAdapting(object):
	implements(IPathAdapter)

	def __init__(self, context, request = None):
		self.context = context
		self.request = request

	def __getitem__(self, path):
		try:
			names = path.split('.')
			moduleName = string.join(names[:-1], '.')
			name = names[-1]
			moduleInstance = __import__(moduleName, globals(), locals(), name)
		except ImportError:
			return None

		interfaceClass = getattr(moduleInstance, name, None)
		if interfaceClass is None:
			return None

		return interfaceClass(self.context, None)
  • configure.zcml
<configure
	xmlns:tales="http://namespaces.zope.org/tales"
	>
	<adapter
			for="*"
			provides="zope.app.traversing.interfaces.IPathAdapter"
			factory=".implements.TalesInterfaceAdapting"
			name="adapt"
			/>
</configure>


こんな風に使う。

<tal:block tal:define="adapted context/adapt:bar.foo.hoge.IRenderer" tal:content="structure adapted/render" />

そうじゃなくても ISized とかいちいち適用すんのウザイっしょ? そんなときのためにあるといいのかも。