root / trunk / samples / calc.rb

Revision 213, 1.4 kB (checked in by why, 10 months ago)

* shoes/ruby.c: adding a span inline, which does just like HTML, for applying adhoc styles.
* samples/: updating some samples with the new methods, still needs lots of work obviously.

Line 
1class Calc
2  def initialize
3    @number = 0
4    @previous = nil
5    @op = nil
6  end
7
8  def to_s
9    @number.to_s
10  end
11 
12  (0..9).each do |n|
13    define_method "press_#{n}" do
14      @number = @number.to_i * 10 + n
15    end
16  end
17
18  def press_clear
19    @number = 0
20  end
21
22  {'add' => '+', 'sub' => '-', 'times' => '*', 'div' => '/'}.each do |meth, op|
23    define_method "press_#{meth}" do
24      if @op
25        press_equals
26      end
27      @op = op
28      @previous, @number = @number, nil
29    end
30  end
31
32  def press_equals
33    @number = @previous.send(@op, @number.to_i)
34    @op = nil
35  end
36
37end
38
39number_field = nil
40number = Calc.new
41Shoes.app :height => 250, :width => 200, :resizable => false do
42  background "#EEC".."#996", :radius => 5,
43    :top => 2, :left => 2, :width => -4, :height => -4
44
45  stack :margin => 4 do
46
47    stack :margin => 8 do
48      number_field = para strong(number)
49    end
50
51    flow :width => 218, :margin => 4 do
52      %w(7 8 9 / 4 5 6 * 1 2 3 - 0 Clr = +).each do |btn|
53        button btn, :width => 46, :height => 46 do
54          method = case btn
55            when /[0-9]/: 'press_'+btn
56            when 'Clr': 'press_clear'
57            when '=': 'press_equals'
58            when '+': 'press_add'
59            when '-': 'press_sub'
60            when '*': 'press_times'
61            when '/': 'press_div'
62          end
63         
64          number.send(method)
65          number_field.replace strong(number)
66        end
67      end
68    end
69  end
70
71end
Note: See TracBrowser for help on using the browser.