Created
May 3, 2011 20:49
-
-
Save boriscy/954202 to your computer and use it in GitHub Desktop.
Examples to not forget metaprogramming
This file contains 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
# 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