Created
November 9, 2016 15:38
-
-
Save chrisroos/af019e8fda761770ce5a31e5d4115df9 to your computer and use it in GitHub Desktop.
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 'test/unit' | |
class Parent | |
class << self | |
def my_class_method | |
'class-method' | |
end | |
def bound_class_method | |
method(:my_class_method) | |
end | |
end | |
end | |
class Child < Parent | |
end | |
class ClassMethodTest < Test::Unit::TestCase | |
def test_should_define_method_using_bound_class_method | |
Parent.class_eval do | |
class << self | |
# In Ruby 1.8.7 passing the bound Method to `define_method` results in | |
# "TypeError: singleton method bound for a different object" | |
# when calling this method from a subclass of the parent (i.e. when | |
# calling `Child.new_class_method`). | |
define_method(:new_class_method, Parent.bound_class_method) | |
# The following implementation works in all ruby versions 1.8.7 up to 2.3 | |
# define_method(:new_class_method) { Parent.bound_class_method.call } | |
end | |
end | |
assert_equal 'class-method', Parent.my_class_method | |
assert_equal 'class-method', Child.my_class_method | |
assert_equal 'class-method', Parent.new_class_method | |
assert_equal 'class-method', Child.new_class_method | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment