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:
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 therequestobject is the first (and only) parameter.This works because, in Ruby, functions can be used with or without parentheses.