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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With