How to access a classes private method

I’m trying to call a classes protected method but I can’t seem to get it
to work. Here’s an example of the method I’m trying to call

moule Foo
Class Bar
protected
def bars_method(a=2)
a
end
end
end

Here’s what the relevant parts of my script look like

def calling_protected_method
result = Foo::Bar.bars_method
end

This is resulting in a method not found error. I know I can’t access a
protected method this way, but I don’t know how to open up the class and
access this method. Thanks in advance for any help.

Charlie B.
http://www.recentrambles.com

Sorry, just realized that the subject said private method, I meant to
say protected.

On Fri, 2006-05-26 at 21:29 +0900, Charlie B. wrote:

end
access this method. Thanks in advance for any help.

Charlie B.
http://www.recentrambles.com

Charlie B.
Programmer
Castle Branch Inc.

Charlie B. wrote:

Sorry, just realized that the subject said private method, I meant to
say protected.

On Fri, 2006-05-26 at 21:29 +0900, Charlie B. wrote:

end
access this method. Thanks in advance for any help.

Charlie B.
http://www.recentrambles.com

Charlie B.
Programmer
Castle Branch Inc.

If you need to access it outside of an instance, why make it protected?
How are you using this?

Anyway, onto the solution:

def calling_protected_method
result = Foo::Bar.new.method(:bars_method).call
end

    def bars_method(a=2)
        a
    end

Here’s what the relevant parts of my script look like

def calling_protected_method
result = Foo::Bar.bars_method
end

You do realize that the whole point of making methods protected is NOT
to be able to call them, right?
-tim

Yes, I’m assuming the reason this method is marked as protected in the
rails framework is so that it can’t be called arbitrarily from the web.
I don’t think I’ll be causing any trouble by calling it from a plugin.

On Fri, 2006-05-26 at 22:15 +0900, Tim B. wrote:

You do realize that the whole point of making methods protected is NOT
to be able to call them, right?
-tim

Charlie B.
http://www.recentrambles.com

On May 26, 2006, at 8:29 AM, Charlie B. wrote:

end

end

Here’s what the relevant parts of my script look like

def calling_protected_method
result = Foo::Bar.bars_method
end

This is wrong for two reasons:

  1. you are calling bars_method on the class object ‘Foo::Bar’ and
    not on an instance of Foo::Bar
  2. the standard calling syntax will trip the protected method check

bar = Foo::Bar.new # get an instance of Foo::Bar
bar.bars_method # method found now but is protected
NoMethodError: protected method `bars_method’ called for #<Foo::Bar:
0x1c8e50>

In order to bypass the protected method check you need to use send,
which ignores visibility attributes (private/protected).

bar.send(:bars_method) # 2
bar.send(:bars_method, “arg1”) # “arg1”

Gary W.