# Some late night metaprogramming

**URL:** <https://www.ruby-forum.com/t/some-late-night-metaprogramming/133642>\
**Category:** Ruby\
**Created:** [April 2, 2008, 8:06am UTC](https://www.ruby-forum.com/t/some-late-night-metaprogramming/133642 "2008-04-02T08:06:00Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Trans](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/dfb087/32.png) [@Trans](https://www.ruby-forum.com/u/Trans)\
**Post date:** [April 2, 2008, 8:06am UTC](https://www.ruby-forum.com/t/some-late-night-metaprogramming/133642/1 "2008-04-02T08:06:00Z")

</div>

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
