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.
Sorry, just realized that the subject said private method, I meant to
say protected.
···
On Fri, 2006-05-26 at 21:29 +0900, Charlie Bowman wrote:
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.
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).
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 Becker wrote:
...
> 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