Skip to content

Instantly share code, notes, and snippets.

@tfausak
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfausak/e4fe3e7e32d19c938038 to your computer and use it in GitHub Desktop.
Save tfausak/e4fe3e7e32d19c938038 to your computer and use it in GitHub Desktop.
A rundown of the many ways to compare classes in Ruby.
# coding: utf-8
require 'rspec' # 2.14.1
# NOTE: "include?" and "included_modules" are for modules only.
CLASS_METHODS = %i(
!=
<
<=
<=>
==
===
>
>=
__id__
ancestors
eql?
equal?
include?
included_modules
inspect
name
object_id
superclass
to_s
)
def fake(klass)
Class.new(BasicObject) do
eigenclass = class << self; self end
eigenclass.extend(Forwardable)
eigenclass.def_delegators(klass, *CLASS_METHODS)
define_method(:instance_of?) { |x| klass == x }
define_method(:is_a?) { |x| klass >= x }
alias_method(:kind_of?, :is_a?)
end
end
describe Object do
let(:fake_klass) { fake(described_class) }
let(:fake_object) { fake_klass.new }
let(:object) { described_class.new }
%i(
__id__
ancestors
included_modules
inspect
name
object_id
superclass
to_s
).each do |method|
it ".#{method}" do
args = [method]
expected = described_class.__send__(*args)
actual = fake_klass.__send__(*args)
expect(actual).to eql expected
end
end
%i(
!=
<
<=
<=>
==
>
>=
eql?
equal?
).each do |method|
it ".#{method}" do
args = [method, described_class]
expected = described_class.__send__(*args)
actual = fake_klass.__send__(*args)
expect(actual).to eql expected
end
end
%i(
include?
).each do |method|
it ".#{method}" do
args = [method, Comparable]
expected = described_class.__send__(*args)
actual = fake_klass.__send__(*args)
expect(actual).to eql expected
end
end
%i(
===
).each do |method|
it ".#{method}" do
[object, fake_object].each do |objekt|
args = [method, objekt]
expected = described_class.__send__(*args)
actual = fake_klass.__send__(*args)
expect(actual).to eql expected
end
end
end
%i(
instance_of?
is_a?
kind_of?
).each do |method|
it "##{method}" do
args = [method, described_class]
expected = object.__send__(*args)
actual = fake_object.__send__(*args)
expect(actual).to eql expected
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment