module RailsRbs::Rules::Equality

Used by the equality default rule type to ensure an objects observed_field equals a specified value.

Public Instance Methods

filter_objects(association) click to toggle source

Return an association of active record objects that have an observed_field value that matches the rules enforced_value. The association is made from the provided association using it as a base to query from. @param association Active record association, relation or collection proxy that supports the where interface

# File lib/rails_rbs/rules/equality.rb, line 30
def filter_objects(association)
  matching_value = self.enforced_value
  # Attempt to coerce the types if we can
  if self.respond_to?(:enforced_type) && self.respond_to?(:force_type)
    matching_value = self.force_type(matching_value)
  end
  association.where("#{self.observed_field} = ?", matching_value)
end
follows_rule?(*objects) click to toggle source

Check one or more object's observed_Field to ensure it equals a specified value contained in the rule's enforced_value field. @param objects [Array<ActiveRecord::Base>] active record object, or objects that respond to the observed_field value of the including rule.

# File lib/rails_rbs/rules/equality.rb, line 9
def follows_rule?(*objects)
  objects.all? do |object|
    source_value, dest_value = object.send(self.observed_field.to_sym), self.enforced_value
    # Attempt to coerce the types if we can
    if self.respond_to?(:enforced_type) && self.respond_to?(:force_type)
      source_value, dest_value = force_type(source_value), force_type(dest_value)
    end
    # Check the comparison operator we use is correct
    return source_value == dest_value if self.try(:comparison_operator).nil? || self.comparison_operator.to_s == '='
    if comparison_operator.to_sym == :=~
      dest_value = Regexp.new(Regexp.escape(dest_value), Regexp::IGNORECASE)
      dest_value = /#{dest_value}/
    end
    source_value.send(self.try(:comparison_operator.to_sym), dest_value)
  end
end