public
Description: Component based Web Development Framework
Homepage:
Clone URL: git://github.com/jnicklas/chianna.git
chianna / calculator.rb
100644 68 lines (55 sloc) 1.279 kb
1
2
3
4
5
6
7
8
9
10
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# This is how I envision this to work somewhere in the future,
# this app doesn't actually work yet!
 
class Calculator < Component
 
  map '/calculator'
 
  attr_persistent :current, :total, :operation
  bind :display
  
  def initialize
    self.current = 0
    self.total = 0
    self.display.text.bind_to! :current
  end
 
  def number(i)
    self.current = (self.current * 10) + i
  end
  
  def operation(op)
    self.compute
    self.operation = op
  end
  
  def compute
    case self.operation
    when '+'
      self.total += self.current
    when '-'
      self.total -= self.current
    when '*'
      self.total *= self.current
    when '/'
      self.total /= self.current
    end
    self.current = 0
    self.operation = nil
  end
 
  def clear
    self.current = 0
    self.total = 0
    self.operation = nil
  end
  
  protected
  
  def render
    div.display! :bind => :display
    
    ol.numbers! do
      (0..9).each do |i|
        li i, :click => [:number, i]
      end
    end
    
    ul.operations! do
      li '+', :click => [:operation, '+']
      li '-', :click => [:operation, '-']
      li '*', :click => [:operation, '*']
      li '/', :click => [:operation, '/']
      li '=', :click => :compute
      li 'AC', :click => :clear
    end
  end
  
end