Last active
August 29, 2015 14:01
-
-
Save tfausak/e4fe3e7e32d19c938038 to your computer and use it in GitHub Desktop.
A rundown of the many ways to compare classes in Ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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