module Volt::Validations::ClassMethods

Public Instance Methods

validate(field_name = nil, options = nil, &block) click to toggle source

Validate is called directly on the class and sets up the validation to be run each time validate! is called on the class.

# File lib/volt/models/validations/validations.rb, line 18
def validate(field_name = nil, options = nil, &block)
  if block
    if field_name || options
      fail 'validate should be passed a field name and options or a block, not both.'
    end
    self.custom_validations ||= []
    custom_validations << block
  else
    self.validations_to_run ||= {}
    validations_to_run[field_name] ||= {}
    validations_to_run[field_name].merge!(options)
  end
end
validations(*run_in_actions, &block) click to toggle source

Validations takes a block, and can contain validate calls inside of it which will conditionally be run based on the code in the block. The context of the block will be the current model.

# File lib/volt/models/validations/validations.rb, line 35
def validations(*run_in_actions, &block)
  unless block_given?
    raise 'validations must take a block, use `validate` to setup a validation on a class directly.'
  end

  # Add a validation block to run during each validation
  validate do
    action = new? ? :create : :update

    if run_in_actions.size == 0 || run_in_actions.include?(action)
      @instance_validations = {}
      @instance_custom_validations = []

      instance_exec(action, &block)

      result = run_validations(@instance_validations)
      result.merge!(run_custom_validations(@instance_custom_validations))

      @instance_validations = nil
      @instance_custom_validations = nil

      result
    end
  end
end