Project

General

Profile

Feature #4910 ยป pro.rb

Example file with old and new variants - rklemme (Robert Klemme), 06/20/2011 08:50 PM

 
1

    
2
class Class
3
  alias call new
4

    
5
  def to_proc(*args)
6
    lambda {|*a| new(*args)}
7
  end
8
end
9

    
10
class Hlp1
11
  def initialize(factory)
12
    @factory = factory
13
  end
14

    
15
  def process(x)
16
    op = @factory.call
17
    op.process x
18
  end
19
end
20

    
21
class Hlp2
22
  def initialize(&factory)
23
    @factory = factory
24
  end
25

    
26
  def process(x)
27
    op = @factory.call
28
    op.process x
29
  end
30
end
31

    
32
# funny name:
33
class Professor
34
  def process(o)
35
    printf "%p: Processing %p...\n", self, o
36
  end
37
end
38

    
39
# call[]
40
puts 'old style'
41
hlp = Hlp1.new lambda { Professor.new }
42
hlp.process "foo"
43
hlp.process "bar"
44

    
45
puts 'with feature'
46
hlp = Hlp1.new Professor
47
hlp.process "foo"
48
hlp.process "bar"
49

    
50
# &callback
51
puts 'old style'
52
hlp = Hlp2.new do Professor.new end
53
hlp.process "foo"
54
hlp.process "bar"
55

    
56
puts 'with feature'
57
hlp = Hlp2.new &Professor
58
hlp.process "foo"
59
hlp.process "bar"
60