Skip to content

Instantly share code, notes, and snippets.

@caius
Created November 8, 2012 22:03
Show Gist options
  • Save caius/4042031 to your computer and use it in GitHub Desktop.
Save caius/4042031 to your computer and use it in GitHub Desktop.
# 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