Sha256: e96b3a58ee87ac06c41f00698f6328b039831cb4c57936f1f27c5f4d7bf5d7bb

Contents?: true

Size: 1.53 KB

Versions: 5

Compression:

Stored size: 1.53 KB

Contents

module Surveyor
  module Models
    module ValidationConditionMethods
      def self.included(base)
        # Associations
        base.send :belongs_to, :validation

        # Scopes

        # Validations
        base.send :validates_presence_of, :operator, :rule_key
        base.send :validates_inclusion_of, :operator, :in => Surveyor::Common::OPERATORS
        base.send :validates_uniqueness_of, :rule_key, :scope => :validation_id
        # this causes issues with building and saving
        # base.send :validates_numericality_of, :validation_id #, :question_id, :answer_id

        base.send :include, Surveyor::ActsAsResponse # includes "as" instance method

        # Class methods
        base.instance_eval do
          def operators
            Surveyor::Common::OPERATORS
          end
        end
      end

      # Instance Methods
      def to_hash(response)
        {rule_key.to_sym => (response.nil? ? false : self.is_valid?(response))}
      end

      def is_valid?(response)
        klass = response.answer.response_class
        compare_to = Response.find_by_question_id_and_answer_id(self.question_id, self.answer_id) || self
        case self.operator
        when "==", "<", ">", "<=", ">="
          response.as(klass).send(self.operator, compare_to.as(klass))
        when "!="
          !(response.as(klass) == compare_to.as(klass))
        when "=~"
          return false if compare_to != self
          !(response.as(klass).to_s =~ Regexp.new(self.regexp || "")).nil?
        else
          false
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
surveyor-0.18.0 lib/surveyor/models/validation_condition_methods.rb
surveyor-0.17.0 lib/surveyor/models/validation_condition_methods.rb
surveyor-0.16.1 lib/surveyor/models/validation_condition_methods.rb
surveyor-0.16.0 lib/surveyor/models/validation_condition_methods.rb
surveyor-0.15.0 lib/surveyor/models/validation_condition_methods.rb