-
Notifications
You must be signed in to change notification settings - Fork 4
/
with_action.rb
40 lines (35 loc) · 945 Bytes
/
with_action.rb
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