Module: ConditionalValidation::ValidationFlag

Defined in:
lib/conditional_validation/validation_flag.rb

Overview

ConditionalValidation::ValidationFlag is extended by model classes to add the validation_flag macro.

Instance Method Summary collapse

Instance Method Details

#validation_flag(*flags) ⇒ Object

Macro method for defining attr_accessor methods, and the associated enable/disable/predicate methods that wrap the attr_acessor methods, for determining when to run validation sets on a model.

Examples:

class User
  validation_flag :address_attributes
end

Parameters:

  • flags (*Array<String>)

    the validation flag names

Raises:

  • (ArgumentError)


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
# File 'lib/conditional_validation/validation_flag.rb', line 15

def validation_flag(*flags)
  raise ArgumentError, "flags can't be empty" if flags.empty?

  accessor_method_names = flags.map { |flag| "_#{flag}_validation_flag" }
  attr_accessor(*accessor_method_names)

  flags.each do |flag|
    # def enable_address_attributes_validation
    # def disable_address_attributes_validation
    # def validate_on_address_attributes?
    class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def enable_#{flag}_validation
        self._#{flag}_validation_flag = true
        self
      end

      def disable_#{flag}_validation
        self._#{flag}_validation_flag = false
        self
      end

      def validate_on_#{flag}?
        !!_#{flag}_validation_flag
      end
    RUBY
  end
end