Class: Wee::Examples::Calculator

Inherits:
Component show all
Defined in:
lib/wee/examples/calculator.rb

Overview

NEEDS: FormDecoration

Instance Method Summary collapse

Methods inherited from Component

#add_decoration, #backtrack_state, #backtrack_state_chain, #decoration, #decoration=, #do_render_chain, #each_decoration, #process_callbacks, #process_callbacks_chain, #remove_decoration, #remove_decoration_if

Methods inherited from Presenter

#backtrack_state, #do_render, #get_property, #lookup_property, #process_callbacks, #properties, #properties=, #session, template, uses_property

Constructor Details

#initializeCalculator

Returns a new instance of Calculator.



4
5
6
7
8
9
# File 'lib/wee/examples/calculator.rb', line 4

def initialize
  super()

  @number_stack = []
  @input = "" 
end

Instance Method Details

#append(str) ⇒ Object



54
55
56
# File 'lib/wee/examples/calculator.rb', line 54

def append(str)
  @input << str 
end

#clearObject



50
51
52
# File 'lib/wee/examples/calculator.rb', line 50

def clear
  @input = ""
end

#enterObject



45
46
47
48
# File 'lib/wee/examples/calculator.rb', line 45

def enter
  @number_stack << @input.to_f
  @input = "" 
end

#operation(op) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/wee/examples/calculator.rb', line 58

def operation(op)
  unless @input.empty?
    @number_stack << @input.to_f
    @input = ""
  end
  if @number_stack.size < 2
    call Wee::MessageBox.new('Stack underflow!')
  else
    r2, r1 = @number_stack.pop, @number_stack.pop
    @number_stack.push(r1.send(op, r2))
  end
end

#renderObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/wee/examples/calculator.rb', line 11

def render
  # the number stack

  r.ul { @number_stack.each {|num| r.li(num)} }

  # the display

  r.text_input.value(@input).readonly

  r.space

  r.submit_button.value("Enter").callback(:enter)

  r.submit_button.value("C").callback(:clear)

  r.break

  # the number buttons

  (0..9).each {|num|
    r.submit_button.value(num).callback(:append, num.to_s)
  }

  # the decimal point

  r.submit_button.value(".").disabled(@input.include?(".")).callback(:append, '.')

  # binary operators

  ['+', '-', '*', '/'].each { |op|
    r.submit_button.value(op).callback(:operation, op)
  }
end