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.
To build on Karmen Blake's answer and KandadaBoggu's answer, the first method definition makes it so when this line is executed:
@blog.req = request
It's like doing this instead:
@blog.user_ip = request.remote_ip
@blog.user_agent = request.env['HTTP_USER_AGENT']
@blog.referrer = request.env['HTTP_REFERER']
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 the request
object is the first (and only) parameter.
This works because, in Ruby, functions can be used with or without parentheses.
That line defines a method called req=
. The =
character in the end makes it an assignment method.
This is a regular setter method:
def foo(para1)
@foo = para1
end
The setter method can be re-written as an assignment method as follows:
def foo=(para1)
@foo = para1
end
Difference between the two setter methods is in the invocation syntax.
Assignment setter:
a.foo=("bar") #valid syntax
a.foo= ("bar") #valid syntax
a.foo = ("bar") #valid syntax
a.foo= "bar" #valid syntax
a.foo = "bar" #valid syntax
Regular setter:
a.foo("bar") #valid syntax
a.foo ("bar") #valid syntax
a.fo o ("bar") #invalid syntax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With