Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange ruby syntax

Tags:

syntax

ruby

what the syntax is in Action Mailer Basics rails guide ?

class UserMailer < ActionMailer::Base
   def welcome_email(user)
      recipients    user.email
      from          "My Awesome Site Notifications <[email protected]>"
      subject       "Welcome to My Awesome Site"
      sent_on       Time.now
      body          {:user => user, :url => "http://example.com/login"}
   end
end

How should i understand the construction, like

from "Some text for this field"

Is it an assignment the value to a variable, called "from" ?

like image 434
AntonAL Avatar asked Dec 02 '22 05:12

AntonAL


2 Answers

No, it's a method call. The name of the method is from, and the argument is a string. In Ruby, parentheses around method calls are optional, so

from "Some text for this field"

is the same as

from("Some text for this field")

Rails (and many Ruby libraries) like to express code in a natural language style, though, so the parentheses-less version reads better, hence why it is used in examples.

like image 169
mipadi Avatar answered Dec 21 '22 23:12

mipadi


It is a call to a method from with the argument "Some text for this field"

The method comes from the ActionMailer::Base class that your UserMailer extends from.

In Ruby the parentheses around a method call are optional unless something would be ambiguous so the statement is equivalent to from("Some text for this field")

Rails has a coding style that prefers to be close to natural language where possible, hence not using parentheses unless necessary.

Calling this method sets an instance variable @from to the value you provide so that it can be used later when sending the message.

Normally when you have accessor methods for getting and setting a variable you would have from= to set the value and from to return the value, however ActionMailer uses something called adv_attr_accessor to define the from method so that if you call it with a parameter then it acts as a setter but if you call it with no parameters then it acts as a getter.

This can be seen in actionmailer-2.x.x/lib/action_mailer/base.rb and actionmailer-2.x.x/lib/action_mailer/adv_attr_accessor.rb

like image 35
mikej Avatar answered Dec 21 '22 22:12

mikej