Last active
May 25, 2017 15:35
-
-
Save dvandersluis/5132a5d0dd5e01bba0546597c5e81da6 to your computer and use it in GitHub Desktop.
Possible solution to the alias puzzle, with benchmarks
This file contains hidden or 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
require 'active_support/core_ext/array/wrap' | |
module OverridableAlias | |
def overridable_alias(name, aliases:, &block) | |
define_method(name) do | |
method = method(name) | |
if method.super_method | |
send(name) # faster than method.call | |
else | |
yield | |
end | |
end | |
Array.wrap(aliases).each do |a| | |
alias_method a, name | |
end | |
end | |
end |
This file contains hidden or 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
class A | |
extend OverridableAlias | |
overridable_alias(:foo, aliases: [:bar, :baz]) do | |
'hello' | |
end | |
end | |
class B < A | |
def foo | |
'bye' | |
end | |
end | |
class C < A | |
end | |
class D | |
def foo | |
'hello' | |
end | |
alias_method :bar, :foo | |
end | |
class E < D | |
def foo | |
'bye' | |
end | |
alias_method :bar, :foo | |
end |
This file contains hidden or 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
require 'benchmark/ips' | |
a = A.new | |
b = B.new | |
c = C.new | |
d = D.new | |
e = E.new | |
Benchmark.ips do |x| | |
x.report("a.bar") { a.bar } | |
x.report("b.bar") { b.bar } | |
x.report("c.bar") { c.bar } | |
x.report("d.bar") { d.bar } | |
x.report("e.bar") { e.bar } | |
x.compare! | |
end |
Author
dvandersluis
commented
May 25, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment