Skip to content

Instantly share code, notes, and snippets.

@mkdynamic
Created December 15, 2013 05:23
Show Gist options
  • Save mkdynamic/7969242 to your computer and use it in GitHub Desktop.
Save mkdynamic/7969242 to your computer and use it in GitHub Desktop.
Use class_eval for monkey patching classes, to avoid forgetting to load the target class and ending up with a more cryptic type error.
# 1. in one file, assuming that Foo is loaded/auto-loaded
class Foo
def monkey_patch
# ...
end
end
# 2. later, the real Foo (in another file) is loaded
class Foo < File
end
# 3. results in a TypeError
#=> TypeError: superclass mismatch for class Foo
#
# vs.
#
# 1. in one file, assuming that Foo is loaded/auto-loaded
Foo.class_eval do
def monkey_patch
# ...
end
end
# 2. results in a NameError, since target class is not yet loaded, forces you to require Foo first.
#=> NameError: uninitialized constant Foo
# 3. the above exception makes you realize Foo is not loaded yet, so you add a require
require 'foo'
Foo.class_eval do
def monkey_patch
# ...
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment