Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 44bd9a3ba2
Daniel Morrison October 26, 2010
file 41 lines (35 sloc) 0.945 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
module WithAction
  def with_action(*actions)
    responder = ActionResponder.new(self)
    yield responder if block_given?
    actions.each {|a| responder.send(a) }
    responder.respond
  end
  
  class ActionResponder
    def initialize(controller)
      @controller = controller
      @order, @responses = [], {}
    end
    
    def respond
      action = @order.detect do |a|
        !@controller.params[a].blank? || !@controller.params["#{a}.x"].blank?
      end
      action ||= @order.include?(:any) ? :any : @order.first
      @responses[action].call if @responses[action]
    end
    
    def any(&block)
      method_missing(:any) do
        # reset
        @order, @responses = [], {}
        block.call.tap do
          respond
        end
      end
    end
    
    def method_missing(action, &block)
      @order << action
      block ||= lambda { @controller.send(action) }
      @responses[action] = block
    end
  end
  
end
Something went wrong with that request. Please try again.