Is there a way to have instance_eval cannot call private/protected method?

Hi,

Is there any mechanism to do what instance_eval but honor the
visibility? I want to something like following, but would like the
block passed to real_object can only only have access to public
methods.

I did a little search, seems like 1.8.5 does that, but was changed in
1.8.6[1]. While I don’t know the history, I am interested to learn
about the rational, and if there is a replacement for that behavior.

Thanks in advance,
Henry

[1]
http://jamesgolick.com/2007/9/28/ruby-1-8-5-_eval-methods-are-subject-to-access-modifiers-on-self.html

class RealObject
private
def method1(param)
puts “Test Method 1: #{param}”
end
public
def method2(param)
puts “Test Method 2: #{param}”
end
end

def real_object(&block)
x = RealObject.new
x.instance_eval &block
end

real_object {
method2 “m2”
method2 “m2.2”
method1 “please fail me”
}

On Jan 25, 10:57 pm, slowhog [email protected] wrote:

Hi,

Is there any mechanism to do what instance_eval but honor the
visibility?

I probably should clarify that I would like to know if there is a
‘right’ way to do it, other than hacking something like another layer
to be the ‘API’ object which hide the real object.

Cheers,
Henry

I don’t think there’s any way to do quite exactly this, since calling,
for example, ‘method2 “m2”’ relies on self being set to an instance of
RealObject. If self is an instance of RealObject, there’s no (sane)
way to hide private methods.

You might want to consider something like:

def real_object(&block)
x = RealObject.new
yield x
end

real_object do |o|
o.method2 “m2”
o.method2 “m2.2”
o.method1 “please fail me”
end

Burke

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs