Rob*_*son 23 ruby ruby-on-rails access-specifier private-methods
来自C风格语法的悠久历史,现在正在尝试学习Ruby(在Rails上),我一直在用它的成语等问题分享我的问题,但今天我遇到了一个我没想到会出现问题的问题.我无法看到任何必须在我面前的东西.
我有一个二进制类,其中包含一个私有方法,用于从路径值派生URI值(uri和路径是类的属性).我打电话self.get_uri_from_path()
从内部Binary.upload()
,但我得到:
Attempt to call private method
Run Code Online (Sandbox Code Playgroud)
该模型的片段如下所示:
class Binary < ActiveRecord::Base
has_one :image
def upload( uploaded_file, save = false )
save_as = File.join( self.get_bin_root(), '_tmp', uploaded_file.original_path )
# write the file to a temporary directory
# set a few object properties
self.path = save_as.sub( Rails.root.to_s + '/', '' )
self.uri = self.get_uri_from_path()
end
private
def get_uri_from_path
return self.path.sub( 'public', '' )
end
end
Run Code Online (Sandbox Code Playgroud)
我打电话不正确吗?我错过了一些更基本的东西吗?目前唯一Binary.get_uri_from_path()
被调用的地方是 - Binary.upload()
.我希望能够在同一个类中调用私有方法,除非Ruby做了与我使用的其他语言明显不同的东西.
谢谢.
mar*_*cgg 46
不要这样做
self.get_uri_from_path()
Run Code Online (Sandbox Code Playgroud)
做
get_uri_from_path()
Run Code Online (Sandbox Code Playgroud)
因为...
class AccessPrivate
def a
end
private :a # a is private method
def accessing_private
a # sure!
self.a # nope! private methods cannot be called with an explicit receiver at all, even if that receiver is "self"
other_object.a # nope, a is private, you can't get it (but if it was protected, you could!)
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15860 次 |
最近记录: |