Some late night metaprogramming

T

Trans

class Module

# Note: view is public, private, protected, or nil.

def def_methods(view=nil, &block)
@defmethods ||= DefMethods.new(self, view)
@defmethods.instance_eval(&block)
end

class DefMethods
private *instance_methods.select{ |m| m !~ /^(__|instance_eval)/ }

def initialize(base, view=nil)
@base = base
@view = view
end

def method_missing(s, *a, &b)
@base.__send__:)define_method, s, &b)
@base.__send__(@view, s) if @view
end
end

end

# Example

class X

def_methods:)public) do

world = "World!"

hello do
"Hello"
end

hello_world do
hello + ' ' + world
end

end

end

x = X.new
puts x.hello_world
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top