Skip to content

Commit

Permalink
remove some evals from callback conditionals
Browse files Browse the repository at this point in the history
  • Loading branch information
tenderlove committed Jun 11, 2013
1 parent ebf2113 commit a63a964
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
5 changes: 4 additions & 1 deletion activemodel/lib/active_model/callbacks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,10 @@ def _define_after_model_callback(klass, callback) #:nodoc:
klass.define_singleton_method("after_#{callback}") do |*args, &block|
options = args.extract_options!
options[:prepend] = true
options[:if] = Array(options[:if]) << "value != false"
conditional = ActiveSupport::Callbacks::Conditionals::Value.new { |v|
v != false
}
options[:if] = Array(options[:if]) << conditional
set_callback(:"#{callback}", :after, *(args << options), &block)
end
end
Expand Down
4 changes: 3 additions & 1 deletion activemodel/lib/active_model/validations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,9 @@ def validate(*args, &block)
if options.key?(:on)
options = options.dup
options[:if] = Array(options[:if])
options[:if].unshift("validation_context == :#{options[:on]}")
options[:if].unshift lambda { |o|
o.validation_context == options[:on]
}
end
args << options
set_callback(:validate, *args, &block)
Expand Down
10 changes: 10 additions & 0 deletions activesupport/lib/active_support/callbacks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ def run_callbacks(kind, &block)
def halted_callback_hook(filter)
end

module Conditionals # :nodoc:
class Value
def initialize(&block)
@block = block
end
def call(target, value); @block.call(value); end
end
end

module Filters
Environment = Struct.new(:target, :halted, :value, :run_block)

Expand Down Expand Up @@ -415,6 +424,7 @@ def make_lambda(filter)
when String
l = eval "lambda { |value| #{filter} }"
lambda { |target, value| target.instance_exec(value, &l) }
when Conditionals::Value then filter
when ::Proc
if filter.arity > 1
return lambda { |target, _, &block|
Expand Down

0 comments on commit a63a964

Please sign in to comment.