File: recorder.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (54 lines) | stat: -rw-r--r-- 1,284 bytes parent folder | download
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
module Sow

  # Manifest captures the actions a generator performs.  Instantiate
  # a manifest with an optional target object, hammer it with actions,
  # then replay or rewind on the object of your choice.
  #
  # Example:
  #   recorder = Recorder.new { |m|
  #     m.make_directory '/foo'
  #     m.create_file '/foo/bar.txt'
  #   }
  #   recorder.replay(creator)
  #   recorder.rewind(destroyer)
  #
  # TODO: Use Facets recorder in future version?

  class Recorder
    attr_reader :target

    # Take a default action target.  Yield self if block given.
    def initialize(target = nil)
      @target, @actions = target, []
      yield self if block_given?
    end

    # Record an action.
    def method_missing(action, *args, &block)
      @actions << [action, args, block]
    end

    # Replay recorded actions.
    def replay(target = nil)
      send_actions(target || @target, @actions)
    end

    # Rewind recorded actions.
    def rewind(target = nil)
      send_actions(target || @target, @actions.reverse)
    end

    # Erase recorded actions.
    def erase
      @actions = []
    end

    private
      def send_actions(target, actions)
        actions.each do |method, args, block|
          target.send(method, *args, &block)
        end
      end
  end

end