[英]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. 我熟悉Java和C,并且相当熟悉Ruby,但有时会被一些Ruby语法搞糊涂。
For instance what is the following line supposed to be? 例如,以下行应该是什么? I assume we are making a function call
protect_from_forgery()
? 我假设我们正在调用函数
protect_from_forgery()
?
But what is the meaning of with: :exception
? 但是具有以下含义是什么
with: :exception
? I guess :exception
is a hash value (eg { :exception => "NullPtr" }
) but what is with:
? 我猜
:exception
是一个哈希值(例如{ :exception => "NullPtr" }
),但是with:
protect_from_forgery with: :exception
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. 当散列的键是符号时,可以通过将冒号放在单词的末尾而不是开头来定义散列和键。 Eg
例如
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. 最后,方法参数周围的括号在Ruby中是可选的。 So:
所以:
protect_from_forgery(with: :exception)
Is the same as: 是相同的:
protect_from_forgery with: :exception
Yes protect_from_forgery
is a methods which takes optional hast argument
optional hast argument 是的
protect_from_forgery
是一个采用optional hast argument
可选的hast参数的方法
Here with:
is a key which is internally a method
and :exception
is value which is also a methods 这里
with:
是一个内部method
的键, :exception
是值,也是一个方法
see this method protect_from_forgery 请参阅此方法protect_from_forgery
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.