Skip to content

Instantly share code, notes, and snippets.

@boriscy
Created May 3, 2011 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save boriscy/954202 to your computer and use it in GitHub Desktop.
Save boriscy/954202 to your computer and use it in GitHub Desktop.
Examples to not forget metaprogramming
# Some examples to not forget Ruby metaprogramming
class Uno
end
module ExtendMethods
def self.included(base)
base.send(:include, ClassMethods)
base.send(:extend, InstanceMethods)
end
module ClassMethods
def hello
puts "Hello from class methods"
end
["hola", "jeje"].each do |v|
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{v}
puts "#{v}"
end
CODE
end
end
module InstanceMethods
def hello
puts "Hello from instance method"
end
end
end
Uno.send(:include, ExtendMethods)
uno = Uno.new
uno.hello
Uno.hello
uno.hola
module InstanceEval
def eval_methods(&block)
instance_eval &block
end
end
Uno.send(:include, InstanceEval)
uno.eval_methods do
puts "-------DSL like Instance eval-------"
hola
hello
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment