Last active
August 29, 2015 14:15
-
-
Save thermistor/8f55ee442e343579d27a to your computer and use it in GitHub Desktop.
A perfect ruby mock
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
# from http://taylor.fausak.me/2014/05/24/class-comparison-in-ruby/ | |
require 'forwardable' | |
def fake(klass) | |
Class.new(BasicObject) do | |
eigenclass = class << self; self end | |
eigenclass.extend Forwardable | |
eigenclass.def_delegators klass, *%i[ | |
< | |
<= | |
<=> | |
== | |
=== | |
> | |
>= | |
__id__ | |
ancestors | |
eql? | |
equal? | |
inspect | |
name | |
object_id | |
to_s | |
] | |
define_method :class do | |
klass | |
end | |
define_method :inspect do | |
"#<#{klass.name}:0x#{'%x' % (__id__ << 1)}>" | |
end | |
alias_method :to_s, :inspect | |
define_method :instance_of? do |other| | |
klass == other | |
end | |
define_method :is_a? do |other| | |
klass >= other | |
end | |
alias_method :kind_of?, :is_a? | |
end | |
end | |
# Usage | |
# FakeCheese = fake(Cheese) | |
# # => Cheese | |
# american = FakeCheese.new | |
# # => #<Cheese:0x7fd8e1e5ba48> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment