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

S

slowhog

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/ru...-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"
}
 
S

slowhog

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 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.= ..

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

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

real_object {
=A0 method2 "m2"
=A0 method2 "m2.2"
=A0 method1 "please fail me"



}
 
B

burke

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
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top