Created
November 8, 2012 22:03
-
-
Save caius/4042031 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
# Assumes ruby 1.9 | |
# klass is expected to be a constant as a string or an actual constant | |
def add_method_to klass, meffod_name, &meffod_body | |
# Make sure we have a constant to work against | |
klass = klass.split("::").inject(Kernel) {|parent, k| parent.const_get(k) } if String === klass | |
# Add the method to the singleton class of our constant (class level method) | |
klass.singleton_class.__send__(:define_method, meffod_name.to_sym, &meffod_body) | |
end | |
class Foo | |
class Bar | |
end | |
end | |
Foo.respond_to?(:blah) # => false | |
add_method_to Foo, :blah do | |
:blah | |
end | |
Foo.respond_to?(:blah) # => true | |
Foo.blah # => :blah | |
Foo.respond_to?(:sed) # => false | |
add_method_to "Foo", :sed do | |
:sed | |
end | |
Foo.respond_to?(:sed) # => true | |
Foo.sed # => :sed | |
Foo::Bar.respond_to?(:fred) # => false | |
add_method_to Foo::Bar, :fred do | |
:fred | |
end | |
Foo::Bar.respond_to?(:fred) # => true | |
Foo::Bar.fred # => :fred | |
Foo::Bar.respond_to?(:george) # => false | |
add_method_to "Foo::Bar", :george do | |
:george | |
end | |
Foo::Bar.respond_to?(:george) # => true | |
Foo::Bar.george # => :george |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment