hey guys !
could a private/protected method be turned into a public one ?
hey guys !
could a private/protected method be turned into a public one ?
Lex W. wrote:
hey guys !
could a private/protected method be turned into a public one ?
class K
private
def m
end
public :m
end
TPR.
Thomas B. wrote:
Lex W. wrote:
hey guys !
could a private/protected method be turned into a public one ?
class K
private
def m
endnow m is private
public :m
and now it is public
end
TPR.
Thank you ! This will come in handy !
Lex W. wrote:
Thank you ! This will come in handy !
Also, it’s possible to bypass the protection using the Object#send
method. This is useful for unit-testing private methods.
On Fri, Sep 5, 2008 at 11:06 PM, Lex W. [email protected] wrote:
could a private/protected method be turned into a public one ?
Sure.
On the one hand you can circumvect access control with Object#send:
object.send(:method_name_even_if_private, …)
And yes, you indeed can change the visibility:
class C
private
def foo
puts "it works"
end
end
c = C.new
begin
c.foo
rescue
puts $!
C.send(:public, :foo)
c.foo
end
# =>
# private method `foo' called for #<C:0x22013c>
# it works
That public is similar to the private call in C, only done out of the
class and via #send because it is private.
It is interesting to note that we’ve been able to call the method on
an object that was created when #foo was private, as the raised
exception proves. That’s because method calls are resolved on a per
call basis due to the dynamic nature of Ruby.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs