使用 ruby/rails 重载方法的属性
我的用户模型中有一个身份验证方法。
我希望能够像那样调用这个方法
User.authenticate(:email => [email protected], :password => "123")
,
User.authenticate(:remember_token => "asdasds41")
正确的方法是什么?
我瞥见了 Rails 源代码(验证函数),我注意到该函数获得 * 属性,但我没有弄清楚 * 代表什么以及如何读取内部变量
Tnx 以提供帮助
I have an authentication method within my User model.
I want to be able to call this method like that
User.authenticate(:email => [email protected], :password => "123")
and
User.authenticate(:remember_token => "asdasds41")
what's the right way to do that?
I gave a glimpse in rails source (validates function) and I noticed that the function get *attributes, but I didn't figure out what the * stands for and how to read the inner variables
Tnx for helping
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所说的方法实际上是采用值的哈希值。散列中的键(例如:remember_token、:email 和:password)充当命名参数,它们在调用语句中出现的顺序并不重要。
另外,散列通常需要用大括号括起来(例如 {...}),但在 Ruby 中,方法中的最后一个参数不需要这些大括号。
您所说的 *attributes 是一种通过数组将动态数量的参数传递给方法的方法。 *attributes 表示法指示 Ruby 将属性扩展为参数列表。
您所说的身份验证方法看起来像这样:
您显然会做一些除了打印出您收到的参数之外的事情。
The method you are speaking of is actually taking a hash of values. The keys within the hash (e.g. :remember_token, :email, and :password) act as named parameters and it does not matter where within the order they appear in the calling statement.
Also, the hash would normally need to be surrounded by braces (e.g. {...}), but in Ruby the last argument in a method does not require these braces.
The *attributes that you speak of is a way to pass a dynamic number of arguments to a method as through an array. The *attributes notation instructs Ruby to expand the attributes into a list of arguments.
The authenticate method you speak of would look something like this:
where you would obviously do something other than print out the parameters that you are receiving.