Skip to content

Instantly share code, notes, and snippets.

@ilake
Created March 15, 2012 08:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ilake/2042942 to your computer and use it in GitHub Desktop.
Save ilake/2042942 to your computer and use it in GitHub Desktop.
metaprograming: define_method, define_singleton_method(1.9)
# base on ruby 1.9
# Reference :
# http://stackoverflow.com/questions/185947/ruby-define-method-vs-def
# define_method is a (private) method of the object Class. You are calling it from an instance. There is no instance method called define_method, so it recurses to your method_missing, this time with :define_method (the name of the missing method), and :screech (the sole argument you passed to define_method).
# http://stackoverflow.com/questions/752717/how-do-i-use-define-method-to-create-class-methods
class Base
def self.meta_instance_method &block
define_method "ins", block
end
def self.meta_class_method &block
define_singleton_method "cls", block
end
end
class Child < Base
meta_instance_method do
"This is meta_instance_method"
end
meta_class_method do
"This is meta_class_method"
end
def method_missing(m)
self.class.send(:define_method, "missing") do
"method_missing"
end
end
end
puts Child.new.ins
puts Child.cls
puts Child.new.missing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment