Skip to content

Instantly share code, notes, and snippets.

@cjheath
Forked from JonRowe/prepend_class.rb
Last active August 29, 2015 13:56
Show Gist options
  • Save cjheath/9261036 to your computer and use it in GitHub Desktop.
Save cjheath/9261036 to your computer and use it in GitHub Desktop.
s = 's';
def s.foo; 'foo'; end
eigen = (class << s; self; end)
def eigen.foo; 'bar'; end # This is unused
def String.foo; 'baz'; end
module Frob
def foo
super+'frob'
end
end
p s.foo
#=> "foo"
class << s; prepend Frob; end
p s.foo
#=> "foofrob"
p s.class.foo
#=> "baz"
class << String; prepend Frob; end
p s.class.foo
#=> "bazfrob"
module B
def a
puts 'b'
super
end
end
class A
class << self; prepend B; end
def self.a
puts 'a'
end
end
class << A
def a
puts 'c'
super
end
end
A.a
# =>
# b
# c
# prepend_class.rb:18:in `a': super: no superclass method `a' for A:Class (NoMethodError)
# from prepend_class.rb:4:in `a'
# from prepend_class.rb:22:in `<main>'
#
# I'm assuming this is because the singleton class is the class, so it redefines the method rather than overriding...
#
#
module B
def a
puts 'b'
super
end
end
class A
prepend B
def a
puts 'a'
end
end
a = A.new
class << a
def a
puts 'c'
super
end
end
a.a
# =>
# c
# b
# a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment