Sha256: 40b5cdd582fc0bbd210fa8bfc23bb5cd0298b9928ce5fed0ef78de4911738128

Contents?: true

Size: 1.47 KB

Versions: 3

Compression:

Stored size: 1.47 KB

Contents

module ConditionalValidation
  module ValidationAccessor
    extend ActiveSupport::Concern

    module ClassMethods
      # Macro method for defining an attr_accessor and various
      # enable/disable/predicate methods that wrap the attr_acessor for
      # determining when to run a set of validation on an ActiveRecord model.
      # @param args [*accessors] the section names for which to define
      #   validation accessors for
      # @example
      #   class User
      #     validation_accessor :address_attributes
      #   end
      #
      #   # => Defines the following methods on instances of the User class:
      #   #      enable_address_attributes_validation
      #   #      disable_address_attributes_validation
      #   #      validate_on_address_attributes?
      def validation_accessor(*accessors)
        attr_accessor *accessors.map { |accessor| "_#{accessor}_validation_accessor" }

        accessors.each do |accessor|
          define_method "enable_#{accessor}_validation" do
            self.send("_#{accessor}_validation_accessor=", true)
            self
          end

          define_method "disable_#{accessor}_validation" do
            self.send("_#{accessor}_validation_accessor=", false)
            self
          end

          define_method "validate_on_#{accessor}?" do
            !!self.send("_#{accessor}_validation_accessor")
          end
        end
      end
    end
  end
end

ActiveRecord::Base.send(:include, ConditionalValidation::ValidationAccessor)

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
conditional_validation-0.0.5 lib/conditional_validation/validation_accessor.rb
conditional_validation-0.0.4 lib/conditional_validation/validation_accessor.rb
conditional_validation-0.0.3 lib/conditional_validation/validation_accessor.rb