Class: PageTemplate::CaseCommand

Inherits:
StackableCommand show all
Defined in:
lib/PageTemplate/case.rb

Overview

CaseCommand provides switch-command functionality.

% case variable %
% when literal1 %
% when literal2 %
% when literal3 %
% else %
% end %

Instance Attribute Summary collapse

Attributes inherited from Command

#called_as

Instance Method Summary collapse

Methods inherited from StackableCommand

#end

Constructor Details

#initialize(value) ⇒ CaseCommand

command is a variable that is evaluated against the namespace on execution, and then tested against the literals of when. It must return a string literal.



24
25
26
27
28
29
30
# File 'lib/PageTemplate/case.rb', line 24

def initialize(value)
  @called_as = 'case'
  @value = value
  @blocks = {}
  @current_case = nil
  @default = BlockCommand.new
end

Instance Attribute Details

#current_caseObject (readonly)

Returns the value of attribute current_case.



20
21
22
# File 'lib/PageTemplate/case.rb', line 20

def current_case
  @current_case
end

Instance Method Details

#add(command) ⇒ Object

Adds a command to the current case, or to the ‘else’



32
33
34
35
36
37
38
# File 'lib/PageTemplate/case.rb', line 32

def add(command)
  unless @current_case
    @default.add command
  else
    @blocks[@current_case].add command
  end
end

#elseObject



44
45
46
47
# File 'lib/PageTemplate/case.rb', line 44

def else
  @current_case = nil
  return true
end

#output(namespace = nil) ⇒ Object

If namespace.get(@value) exists in the ‘when’ clauses, then print out that block.



50
51
52
53
54
55
56
57
# File 'lib/PageTemplate/case.rb', line 50

def output(namespace=nil)
  val = namespace.get(@value,false)
  if @blocks.has_key?(val)
    @blocks[val].output(namespace)
  else
    @default.output(namespace)
  end
end

#to_sObject



58
59
60
61
62
63
64
65
# File 'lib/PageTemplate/case.rb', line 58

def to_s
  str = "[ Case: "
  @blocks.each do |key,val|
    str << " #{key}: [#{val}]"
  end
  str << " else #{@default.to_s}"
  str << " ]"
end

#when(value) ⇒ Object

‘when’ and ‘else’ modify this command.



40
41
42
43
# File 'lib/PageTemplate/case.rb', line 40

def when(value)
  @current_case = value
  @blocks[value] = BlockCommand.new unless @blocks.has_key?(value)
end