Reputation: 3081
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
Upvotes: 5
Views: 269
Reputation: 2246
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
Upvotes: 9
Reputation: 10358
Yes protect_from_forgery
is a methods which takes optional hast argument
optional hast argument
Here with:
is a key which is internally a method
and :exception
is value which is also a methods
see this method protect_from_forgery
Upvotes: 0