[View] [Edit] [Attachments] [History] [Home] [Changes] [Search] [Help]

SmallWiki のアクセスカウンタ

Uploaded Image: counter.gif
心の準備が出来たところで、SmallWiki の部品を作ってみよう。まず、簡単そうなアクセスカウンタ。
コードを先に見てもらいます。
'From Squeak3.7alpha of ''11 September 2003'' [latest update: #5657] on 6 February 2004 at 6:38:19 pm'!
SWTemplateBody subclass: #SWTemplateCounter
	instanceVariableNames: 'counter'
	classVariableNames: ''
	poolDictionaries: ''
	category: 'SmallWiki-Counter'!

!SWTemplateCounter methodsFor: 'rendering' stamp: 'tak 2/6/2004 18:37'!
renderBodyWith: anAction on: html
	counter _ counter + 1.
	self renderDivFor: anAction on: html with: [
		html render: counter].
! !


!SWTemplateCounter methodsFor: 'initialization' stamp: 'tak 2/6/2004 18:32'!
initialize
	super initialize.
	counter _ 0.! !

"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!

SWTemplateCounter class
    instanceVariableNames: ''!

!SWTemplateCounter class methodsFor: 'accessing' stamp: 'tak 2/6/2004 18:19'!
title
    ^'Counter'! !

クラス定義

SWTemplateBody subclass: #SWTemplateCounter
	instanceVariableNames: 'counter'
	classVariableNames: ''
	poolDictionaries: ''
	category: 'SmallWiki-Counter'!

このように、部品は SWTemplateBody のサブクラスとして作ります。もう一つ SWTemplateHead というのもあって、これはヘッダに部品を追加する時に使います。
アクセス数を保存する為に counter という変数を定義し、#initialize 内で初期化しておきます。

名前を付ける

もう一つ大切な仕事が、テンプレートに名前を付けることです。これにはクラス側の #title で定義します。ここまで作ると、ブラウザのテンプレート設定画面で新しい部品を指定する事が出来ます。
!SWTemplateCounter class methodsFor: 'accessing' stamp: 'tak 2/6/2004 18:19'!
title
    ^'Counter'! !

表示

リクエストがあった場合の処理を #renderBodyWith:on: で行います。引数として渡される html は SWHtmlWriteStream で、まー、モーフの drawOn: における aCanvas のような物です。この流儀は良く分からないので、他の implements をよく読んで参考にしましょう。表示ついでにカウンタの値を一つ上げています。
!SWTemplateCounter methodsFor: 'rendering' stamp: 'tak 2/6/2004 18:37'!
renderBodyWith: anAction on: html
	counter _ counter + 1.
	self renderDivFor: anAction on: html with: [
		html render: counter].


設定

Uploaded Image: counterSetting.gif
作ったカウンタを表示させるには、こんな風にテンプレート画面で設定します。

改良点

見ての通りこのカウンタでは役に立ちません。改良点としては以下の通り。

Link to this Page

propella home