class ActiveHash::Relation::Condition

Attributes

constraints[R]
inverted[R]

Public Class Methods

new(constraints) click to toggle source
# File lib/active_hash/condition.rb, line 4
def initialize(constraints)
  @constraints = constraints
  @inverted = false
end

Public Instance Methods

invert!() click to toggle source
# File lib/active_hash/condition.rb, line 9
def invert!
  @inverted = !inverted

  self
end
matches?(record) click to toggle source
# File lib/active_hash/condition.rb, line 15
def matches?(record)
  match = begin
    return true unless constraints

    expectation_method = inverted ? :any? : :all?

    constraints.send(expectation_method) do |attribute, expected|
      value = record.read_attribute(attribute)

      matches_value?(value, expected)
    end
  end

  inverted ? !match : match
end

Private Instance Methods

matches_value?(value, comparison) click to toggle source
# File lib/active_hash/condition.rb, line 33
def matches_value?(value, comparison)
  return comparison.any? { |v| matches_value?(value, v) } if comparison.is_a?(Array)
  return comparison.cover?(value) if comparison.is_a?(Range)
  return comparison.match?(value) if comparison.is_a?(Regexp)

  normalize(value) == normalize(comparison)
end
normalize(value) click to toggle source
# File lib/active_hash/condition.rb, line 41
def normalize(value)
  value.respond_to?(:to_s) ? value&.to_s : value
end