How to create activerecord style validations outside of activerecord?

后端 未结 2 821
一个人的身影
一个人的身影 2021-01-24 08:17

I am working on a testing framework for the software that my company writes. Our product is web based and After I run a RESTful request I want to process the results. I want t

相关标签:
2条回答
  • 2021-01-24 08:24

    Without having looked much at your code, here's my take on implementing validation class methods:

    module Validations
      def self.included(base)
        base.extend ClassMethods
      end
    
      def validate
        errors.clear
        self.class.validations.each {|validation| validation.call(self) }
      end
    
      def valid?
        validate
        errors.blank?
      end
    
      def errors
        @errors ||= {}
      end
    
      module ClassMethods
        def validations
          @validations ||= []
        end
    
        def validates_presence_of(*attributes)
          validates_attributes(*attributes) do |instance, attribute, value, options|
            instance.errors[attribute] = "cant't be blank" if value.blank?
          end
        end
    
        def validates_format_of(*attributes)
          validates_attributes(*attributes) do |instance, attribute, value, options|
            instance.errors[attribute] = "is invalid" unless value =~ options[:with]
          end
        end
    
        def validates_attributes(*attributes, &proc)
          options = attributes.extract_options!
    
          validations << Proc.new { |instance|
            attributes.each {|attribute|
              proc.call(instance, attribute, instance.__send__(attribute), options)
            }
          }
        end
      end
    end
    

    It assumes that ActiveSupport is around, which it is in a Rails environment. You might want to extend it to allow multiple errors per attribute, with instance.errors[attribute] << "the message", but I left out obscurities like that in order to keep this short sample as simple as possible.

    Here's a short usage example:

    class MyClass
      include Validations
    
      attr_accessor :foo
      validates_presence_of :foo
      validates_format_of :foo, :with => /^[a-z]+$/
    end
    
    a = MyClass.new
    puts a.valid?
    # => false
    
    a.foo = "letters"
    puts a.valid?
    # => true
    
    a.foo = "Oh crap$(!)*#"
    puts a.valid?
    # => false
    
    0 讨论(0)
  • 2021-01-24 08:27

    You want Validatable: sudo gem install validatable

    class Person
      include Validatable
      validates_presence_of :name
      attr_accessor :name
    end
    

    Also, Validatable does not have a dependency on ActiveSupport.

    0 讨论(0)
提交回复
热议问题