Sha256: 58ab0ebeae132d10bc5c3839a0cd79d85891da4e31a7fa0e6d990f352c021584

Contents?: true

Size: 1.72 KB

Versions: 2

Compression:

Stored size: 1.72 KB

Contents

require 'active_record'
require 'active_record/base'
require 'active_record/validations'

module ValidationMirror
  StandardValidations = ActiveRecord::Validations::ClassMethods.instance_methods.grep(/_of$/)
  Validation = Struct.new(:attribute, :macro, :arguments)
  
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    
    def self.define_validation_method_with_capture(validation_name)
      class_eval <<-EOC
        def #{validation_name}_with_capture(*args, &block)
          #{validation_name}_without_capture(*args, &block)
          capture_validation(#{validation_name.inspect}, *args, &block)
        end
      EOC
    end
    
    ValidationMirror::StandardValidations.each { |validation| define_validation_method_with_capture(validation) }
      
    def self.extended(base)
      base.instance_eval do 
        class_inheritable_hash :validations
        write_inheritable_hash :validations, {}
      end
      ValidationMirror::StandardValidations.each do |validation|
        (class << base; self; end).instance_eval { alias_method_chain validation, :capture }
      end
    end
    
    def capture_validation(validation_name, *args, &block)
      options = args.extract_options!
      attrs = args
      attrs.each do |attr|
        new_validations = (validations[attr.to_sym] || []) + [ValidationMirror::Validation.new(attr.to_sym, validation_name.to_sym, options)]
        write_inheritable_hash :validations, {attr.to_sym => new_validations}
      end
    end
    
    def reflect_validations_on(attr)
      validations[attr.to_sym]
    end
    
    def reflect_all_validations
      validations.values.flatten
    end
  end # ClassMethods
end

ActiveRecord::Base.instance_eval { include ValidationMirror }

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
validation-mirror-1.0.1 lib/validation-mirror.rb
validation-mirror-1.0.0 lib/validation-mirror.rb