Hello world example with Environments
Last updated at 11:56 am UTC on 3 March 2017
| createHelloClass createHelloMethod english spanish |
"Straight but verbose code to create a Hello class and compile a say method.
There's one trick: Environment current, otherwise Compiler would evaluate in nil class environment, not good"
createHelloClass := [Object subclass: #Hello
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Test'].
createHelloMethod := [:greeting |
| methodSource sourceCode |
methodSource := 'say Transcript cr; show: ' , greeting printString.
sourceCode := 'Hello class compile: ' , methodSource printString , ' classified: ' , 'test' printString.
Compiler evaluate: sourceCode environment: Environment current].
"Create the english and spanish environments"
english := Smalltalk globals.
spanish := Environment withName: 'Spanish'.
spanish importSelf.
spanish from: english import: #Transcript.
"Create the class and compile the method in each environment:"
[createHelloClass value.
createHelloMethod value: 'Hello world'] on: CurrentEnvironment do: [:exc | exc resume: english].
[createHelloClass value.
createHelloMethod value: 'Buenos dias'] on: CurrentEnvironment do: [:exc | exc resume: spanish].
"Greet"
Compiler evaluate: 'Hello say' environment: english.
Compiler evaluate: 'Hello say' environment: spanish.
Compiler evaluate: 'Hello say' environment: english.
"Cleanup"
[Compiler evaluate: 'Hello removeFromSystem' environment: Environment current] on: CurrentEnvironment do: [:exc | exc resume: english].
[Compiler evaluate: 'Hello removeFromSystem' environment: Environment current] on: CurrentEnvironment do: [:exc | exc resume: spanish].
Comment
Yes, a DynamicVariable:
CurrentEnvironment value: english during: ["load something"].
would be nicer than:
["load something"] on: CurrentEnvironment do: [:exc | exc resume: english].
Otherwise we could fileIn some chunk format stream thru en EnvironmentLoader for: english...
Continue
Updated version of this example