[英]Ruby on Rails Private Methods?
If I'm writing a private method, does rails think that every method under the word private
is going to be private? 如果我正在写一个私有方法,那么rails会认为private
这个词下的每个方法都是私有的吗? or is it supposed to be only private for the first method? 或者它应该只对第一种方法是私有的?
private
def signed_in_user
redirect_to signin_url, notice: "Please sign in." unless signed_in?
end
def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end
does that mean signed_in_user
and correct_user
is private? 这是否意味着signed_in_user
和correct_user
是私有的? or just signed_in_user
? 还是只signed_in_user
? Does that mean whenever I need to write private methods, it should be at the end of my file now? 这是否意味着每当我需要编写私有方法时,它应该在我的文件的末尾?
Yes, each method after the private
keyword will be private. 是的, private
关键字之后的每个方法都是私有的。 If you want to change back to defining non-private methods, you can use a different keyword, like public
or protected
. 如果要更改回定义非私有方法,可以使用其他关键字,如public
或protected
。
See Where to place private methods in Ruby? 请参阅在Ruby中放置私有方法的位置?
Yes all the methods under private
are private. 是private
所有方法都是私有的。 Usually you will, indeed, find those methods at the bottom of your file. 通常,您确实会在文件底部找到这些方法。
But you can "stop" this by writing another keyword like protected
and then all the methods following would be protected. 但是你可以通过编写另一个像protected
这样的关键字来“停止”它,然后protected
所有后面的方法。
Or you can even define your access control in this way too, listing your methods as arguments to the access control functions (public, protected, private): 或者您甚至可以通过这种方式定义访问控制,将您的方法列为访问控制功能的参数(public,protected,private):
class SomeClass
def method1
...
end
def method2
...
end
def method3
...
end
# ... more methods def
public :method1, method4
protected :method3
private :method2
end
As others have written, Every method that follows the private keyword immediately is private in Ruby. 正如其他人所写的那样,随后在private关键字后面的每个方法都是私有的。 This is plain Ruby syntax and has nothing to do with rails. 这是简单的Ruby语法,与rails无关。
private
.....
def pvt_meth_1
.....
end
def pvt_meth_2
.....
end
public
def pub_meth_1
......
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.