Module: ValidationGroup::ActiveRecord::InstanceMethods

Defined in:
lib/spree_core/validation_group.rb

Overview

included in every model which calls validation_group

Instance Method Summary collapse

Instance Method Details

#disable_validation_groupObject



73
74
75
76
77
# File 'lib/spree_core/validation_group.rb', line 73

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 && group_classes.include?(group) end if found group_classes[group].each do |field| self = nil end end end



58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/spree_core/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].clone
  end
end

#reject_non_validation_group_errorsObject



79
80
81
82
# File 'lib/spree_core/validation_group.rb', line 79

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)


87
88
89
# File 'lib/spree_core/validation_group.rb', line 87

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)


97
98
99
100
# File 'lib/spree_core/validation_group.rb', line 97

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)


91
92
93
# File 'lib/spree_core/validation_group.rb', line 91

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