aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails_generator/manifest.rb
blob: 702effa76f5b2fe419a6d98d2a5278014aab7f59 (plain) (blame)
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
module Rails
  module Generator

    # 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:
    #   manifest = Manifest.new { |m|
    #     m.make_directory '/foo'
    #     m.create_file '/foo/bar.txt'
    #   }
    #   manifest.replay(creator)
    #   manifest.rewind(destroyer)
    class Manifest
      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
end