对方法定义感到困惑:def req=(request)
我在 Ryan Bates 的 Railscast 网站上找到了这个,但不确定它是如何工作的。
#models/comment.rb
def req=(request)
self.user_ip = request.remote_ip
self.user_agent = request.env['HTTP_USER_AGENT']
self.referrer = request.env['HTTP_REFERER']
end
#blogs_controller.rb
def create
@blog = Blog.new(params[:blog])
@blog.req = request
if @blog.save
...
我看到他正在保存用户 IP、用户代理和引荐来源网址,但对 req=(request)
行感到困惑。
I found this in Ryan Bates' railscast site, but not sure how it works.
#models/comment.rb
def req=(request)
self.user_ip = request.remote_ip
self.user_agent = request.env['HTTP_USER_AGENT']
self.referrer = request.env['HTTP_REFERER']
end
#blogs_controller.rb
def create
@blog = Blog.new(params[:blog])
@blog.req = request
if @blog.save
...
I see he is saving the user ip, user agent and referrer, but am confused with the req=(request)
line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以 Karmen 为基础进行构建布莱克的回答和KandadaBoggu 的回答,第一个方法定义使得当执行此行时:
这就像这样做:
它基本上设置了一个快捷方式。看起来您只是分配一个变量的值,但实际上您正在调用一个名为
req=
的方法,并且request
对象是第一个(也是唯一的)参数。这是可行的,因为在 Ruby 中,函数可以带或不带括号使用。
To build on Karmen Blake's answer and KandadaBoggu's answer, the first method definition makes it so when this line is executed:
It's like doing this instead:
It basically sets up a shortcut. It looks like you're just assigning a variable's value, but you're actually calling a method named
req=
, and therequest
object is the first (and only) parameter.This works because, in Ruby, functions can be used with or without parentheses.
该行定义了一个名为
req=
的方法。最后的=
字符使其成为一种赋值方法。这是一个常规的 setter 方法:
setter 方法可以重写为赋值方法,如下所示:
两个 setter 方法之间的区别在于调用语法。
作业设置者:
常规设置者:
That line defines a method called
req=
. The=
character in the end makes it an assignment method.This is a regular setter method:
The setter method can be re-written as an assignment method as follows:
Difference between the two setter methods is in the invocation syntax.
Assignment setter:
Regular setter:
但是,在调用方法时,使用赋值而不是参数传递,您会得到看起来更漂亮、更自然的语句。
希望
有帮助。
However, when calling the methods you get a little nicer more natural looking statement using an assignment rather than argument passing.
vs.
Hope that helps.