Module: Sinclair::Comparable

Extended by:
ActiveSupport::Concern
Included in:
Options
Defined in:
lib/sinclair/comparable.rb,
lib/sinclair/comparable/class_methods.rb

Overview

Concern to be added on classes for easy == comparison

Examples:

class SampleModel
  include Sinclair::Comparable

  comparable_by :name
  attr_reader :name, :age

  def initialize(name: nil, age: nil)
    @name = name
    @age  = age
  end
end

model1 = model_class.new(name: 'jack', age: 21)
model2 = model_class.new(name: 'jack', age: 23)

model1 == model2 # returns true

Author:

  • darthjee

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#==(other) ⇒ Boolean

Checks if an instance of a comparable is equals another

Examples:

class SampleModel
  include Sinclair::Comparable

  comparable_by :name
  attr_reader :name, :age

  def initialize(name: nil, age: nil)
    @name = name
    @age  = age
  end
end

model1 = model_class.new(name: 'jack', age: 21)
model2 = model_class.new(name: 'jack', age: 23)

model1 == model2 # returns true

Parameters:

  • other (Object)

    an object that should be equal to comparable

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
45
# File 'lib/sinclair/comparable.rb', line 37

def ==(other)
  klass = self.class
  superklass = klass.superclass

  return false unless klass.equals_checker.match?(self, other)
  return true unless superklass.include?(Sinclair::Comparable)

  superklass.equals_checker.match?(self, other)
end