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
55
56
57
58
|
# File 'lib/batch_actions/class_methods.rb', line 7
def batch_action(keyword, opts = {}, &block)
@batch_actions = {} if @batch_actions.nil?
if opts.include? :model
model = opts[:model]
elsif !@batch_model.nil?
model = @batch_model
else
raise ArgumentError, "model must be specified"
end
if block_given?
apply = block
else
raise ArgumentError, "block must be specified"
end
if opts.include? :scope
scope = opts[:scope]
else
scope = ->(ids) do
model.where(:id => ids)
end
end
if opts.include? :if
condition = opts[:if]
else
condition = ->() { true }
end
@batch_actions[keyword] = condition
raise ArgumentError, "unexpected number of arguments for scope" if scope.arity < 1 || scope.arity > 2
define_method(:"batch_#{keyword}") do
result = instance_exec(&condition)
raise ActionController::RoutingError.new('batch action is not allowed') unless result
case scope.arity
when 1
objects = instance_exec(params[:ids], &scope)
when 2
objects = instance_exec(params[:ids], model.where(:id => params[:ids]), &scope)
end
instance_exec(objects, &apply)
end
end
|