Module: ValidationGroup::ActiveRecord::InstanceMethods

Defined in:
lib/validation_group.rb

Overview

included in every model which calls validation_group

Instance Method Summary collapse

Instance Method Details

#disable_validation_groupObject



75
76
77
78
79
# File 'lib/validation_group.rb', line 75

def disable_validation_group
  @current_validation_group = nil
  # jeffp: delete fields
  @current_validation_fields = nil
end

#enable_validation_group(group) ⇒ Object

def reset_fields_for_validation_group(group)

  group_classes = self.class.validation_group_classes
  found = ValidationGroup::Util.current_and_ancestors(self.class).find do |klass|
    group_classes[klass] && group_classes[klass].include?(group)
  end
  if found
    group_classes[found][group].each do |field|
      self[field] = nil
    end
  end
end


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/validation_group.rb', line 58

def enable_validation_group(group)
  # Check if given validation group is defined for current class or one of
  # its ancestors
  group_classes = self.class.validation_group_classes
  found = ValidationGroup::Util.current_and_ancestors(self.class).
    find do |klass|
    group_classes[klass] && group_classes[klass].include?(group)
  end
  if found
    @current_validation_group = group
    # jeffp: capture current fields for performance optimization
    @current_validation_fields = group_classes[found][group]
  else
    raise ArgumentError, "No validation group of name :#{group}"
  end
end

#reject_non_validation_group_errorsObject



81
82
83
84
# File 'lib/validation_group.rb', line 81

def reject_non_validation_group_errors
  return unless validation_group_enabled?
  self.errors.remove_on(@current_validation_fields)
end

#should_validate?(attribute) ⇒ Boolean

jeffp: optimizer for someone writing custom :validate method – no need to validate fields outside the current validation group note: could also use in validation modules to improve performance

Returns:

  • (Boolean)


89
90
91
# File 'lib/validation_group.rb', line 89

def should_validate?(attribute)
  !self.validation_group_enabled? || (@current_validation_fields && @current_validation_fields.include?(attribute.to_sym))
end

#valid_with_validation_group?(group = nil) ⇒ Boolean

eliminates need to use :enable_validation_group before :valid? call – nice

Returns:

  • (Boolean)


99
100
101
102
# File 'lib/validation_group.rb', line 99

def valid_with_validation_group?(group=nil)
  self.enable_validation_group(group) if group
  valid_without_validation_group?
end

#validation_group_enabled?Boolean

Returns:

  • (Boolean)


93
94
95
# File 'lib/validation_group.rb', line 93

def validation_group_enabled?
  respond_to?(:current_validation_group) && !current_validation_group.nil?
end