Skip to content

Commit

Permalink
simple handling of :if and :unless options
Browse files Browse the repository at this point in the history
  • Loading branch information
kv109 committed Dec 18, 2015
1 parent 0a9b5b4 commit 04bfcba
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/html5_validators/action_view/form_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def form_for(record, options = {}, &block)
module PresenceValidator
def render
if object.class.ancestors.include?(ActiveModel::Validations) && (object.auto_html5_validation != false) && (object.class.auto_html5_validation != false)
@options["required"] ||= @options[:required] || object.class.attribute_required?(@method_name)
@options["required"] ||= @options[:required] || object.class.attribute_required?(object, @method_name)
end
super
end
Expand Down
33 changes: 30 additions & 3 deletions lib/html5_validators/active_model/helper_methods.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
module ActiveModel
module Validations
module HelperMethods
def attribute_required?(attribute)
self.validators.grep(PresenceValidator).any? do |v|
v.attributes.include?(attribute.to_sym) && (v.options.keys & [:if, :unless]).empty?
def attribute_required?(object, attribute)
validator = object.class.validators.grep(PresenceValidator).find { |v| v.attributes.include?(attribute.to_sym) }
return false unless validator

if cant_handle_conditions?(validator)
(validator.options.keys & [:if, :unless]).empty?
else
if_condition = if_condition(validator)
return object.send(if_condition) if can_handle_condition?(if_condition)

unless_condition = unless_condition(validator)
return !object.send(unless_condition) if can_handle_condition?(unless_condition)
end
end

Expand All @@ -30,6 +39,24 @@ def attribute_min(attribute)
v.attributes.include?(attribute.to_sym) && (v.options.keys & [:greater_than, :greater_than_or_equal_to]).any? && (v.options.keys & [:if, :unless, :allow_nil, :allow_blank]).empty?
}.map {|v| v.options.slice(:greater_than, :greater_than_or_equal_to)}.map(&:values).flatten.min
end

private

def unless_condition(validator)
validator.options[:unless]
end

def if_condition(validator)
validator.options[:if]
end

def can_handle_condition?(condition)
condition.is_a?(Symbol)
end

def cant_handle_conditions?(validator)
!can_handle_condition?(if_condition(validator)) && !can_handle_condition?(unless_condition(validator))
end
end
end
end

0 comments on commit 04bfcba

Please sign in to comment.