Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about method definition: def 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.

like image 332
sent-hil Avatar asked Apr 16 '10 05:04

sent-hil


2 Answers

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.

like image 111
Christopher Parker Avatar answered Sep 27 '22 22:09

Christopher Parker


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
like image 31
Harish Shetty Avatar answered Sep 27 '22 22:09

Harish Shetty