Confused by the method definition: def req = (query)

I found this on the railscast site of Ryan Bates, 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 that it saves the user ip, user agent and referrer, but the req=(request) line doesn't bother me.

+6
ruby-on-rails railscasts
source share
3 answers

To build Carmen Blake 's answer and KandadaBoggu's answer , the first method definition does this when it is executed:

 @blog.req = request 

He likes to do this:

 @blog.user_ip = request.remote_ip @blog.user_agent = request.env['HTTP_USER_AGENT'] @blog.referrer = request.env['HTTP_REFERER'] 

Basically it sets a shortcut. It sounds like you are just assigning a variable value, but in fact you are calling a method called req= , and the request object is the first (and only) parameter.

This works because in Ruby functions can be used with or without parentheses.

+6
source share

This line defines a method called req= . The = symbol at the end makes it an assignment method.

This is the usual setter method:

 def foo(para1) @foo = para1 end 

The setter method can be rewritten as an assignment method as follows:

 def foo=(para1) @foo = para1 end 

The difference between the two setter methods is the syntax of the call.

Appointment:

 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 
+6
source share
 def name=(new_name) @name = new_name end has the same functionality as: def name(new_name) @name = new_name end 

However, when you invoke methods, you get a slightly more natural look, using assignment rather than passing arguments.

 person = Person.new person.name = "John Doe" 

against.

 person.name("John Doe") 

Hope this helps.

+2
source share

All Articles