Sha256: d2d5ce441d4ed3c5d2908c5e2837350f556b9bf2dbd9e83b40266ba5ea441429

Contents?: true

Size: 917 Bytes

Versions: 3

Compression:

Stored size: 917 Bytes

Contents

module NubeFact::Validator
  # Following methods solve the issue of having required fields inherits from a base class

  def self.included(klass)
    klass.extend ClassMethods
  end

  module ClassMethods
    # When a class is inherited eg. Invoice, it sets the required fields from 
    # the base class eg. Document to use it as a base
    def inherited(child_class)
      child_class.instance_variable_set :@required_fields, self.required_fields
    end

    def add_required_fields(*fields)
      @required_fields = required_fields + fields
    end

    def required_fields
      @required_fields || []
    end
  end

  def validate!
    #ToDO change for a real validator like ActiveModel::Validations or Hanami::Validations
    self.class::required_fields.each do |field|
      if send(field).nil?
        raise NubeFact::ValidationError.new "#{field} it's a required field."
      end
    end
    true
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
nubefact-0.0.14 lib/util/validator.rb
nubefact-0.0.13 lib/util/validator.rb
nubefact-0.0.12 lib/util/validator.rb