Forum: Ruby Selective runtime provision of instance methods

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Bea287582f4125fa81a2ca945bd48753?d=identicon&s=25 Julian I. Kamil (Guest)
on 2006-03-17 23:46
(Received via mailing list)
I'd like to get some comments and suggestions from anyone who may have
an opinion on this or know of a better way to accomplish this.

I have an object with a lot of methods and variables some of which (but
not all) I'd like to make callable from another object that happens to
be evaluated by ERB.  So I did this:

class LotsOfMethods
    # to be made callable
    def method1 ... end
    def method2 ... end

    # not callable
    def methodX ... end

    def delegate
        d ={
            :var1 => var1,
            :var2 => var2,

        my = self
        d_singleton = class << d; self end
        d_singleton.send(:define_method, :method1) { my.method1 }
        d_singleton.send(:define_method, :method2) { my.method2 }


class Sandbox
    def self.env(delegate) {}

sacred_object =
output =

The idea is that the embedded Ruby code in "text" will be able to
access the specified variables and methods in 'delegate' but not any
others.  So, for example:

text = '<%= delegate.method1 %>'

will be allowed; but:

text = '<%= delegate.methodX %>'

will raise an exception.

Does anyone know of a better way to accomplish the same effect?

Best regards,

Julian I. Kamil <> - Pandora Publisher - The Ruby Bookshelf
This topic is locked and can not be replied to.