Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Ruby/Rails syntax

I am familiar with Java and C and reasonably comfortable with Ruby but get confused by some of the Ruby syntax at times.

For instance what is the following line supposed to be? I assume we are making a function call protect_from_forgery()?
But what is the meaning of with: :exception? I guess :exception is a hash value (e.g { :exception => "NullPtr" } ) but what is with:?

protect_from_forgery with: :exception
like image 949
user2399453 Avatar asked Dec 16 '14 05:12

user2399453


People also ask

What syntax does Ruby use?

The syntax of the Ruby programming language is broadly similar to that of Perl and Python. Class and method definitions are signaled by keywords, whereas code blocks can be defined by either keywords or braces. In contrast to Perl, variables are not obligatorily prefixed with a sigil.

Is Ruby on Rails for beginners?

This guide is designed for beginners who want to get started with creating a Rails application from scratch. It does not assume that you have any prior experience with Rails. Rails is a web application framework running on the Ruby programming language.

What does :: In Ruby mean?

The use of :: on the class name means that it is an absolute, top-level class; it will use the top-level class even if there is also a TwelveDaysSong class defined in whatever the current module is.


1 Answers

There is a far bit of syntactic sugar happening in that line. What I think is tripping you up is the shorthand for hashes and symbols. If you're not familiar with symbols, see here for a good tutorial.

With all the syntactic sugar removed, the line could be written as:

protect_from_forgery({:with => :exception})

Breaking it down, the last argument sent to a method is treated as a hash even without the curly braces. So:

protect_from_forgery({:with => :exception})

Is the same as:

protect_from_forgery(:with => :exception)

When a hash's key is a symbol, the hash and key can be defined by putting the colon at the end of the word instead of the beginning. E.g

protect_from_forgery(:with => :exception)

Is the same as:

protect_from_forgery(with: :exception)

Lastly, the brackets around the arguments of a method are optional in Ruby. So:

protect_from_forgery(with: :exception)

Is the same as:

protect_from_forgery with: :exception
like image 101
Pete Avatar answered Sep 24 '22 14:09

Pete