I'm learning about Factory Girl and I saw this code:
factory :post do
association :author, factory: :user, last_name: "Writely"
end
why do factory
and last_name
have a colon at their end?
The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.
Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.
The fat comma (also termed hash rocket in Ruby and a fat arrow in JavaScript) is a syntactic construction that appears in a position in a function call (or definition) where a comma would usually appear. The original usage refers to the " ) letters :( " construction in ALGOL 60.
What is symbol. Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.
The colon in this context denotes a literal Hash.
factory
is the Hash
key, :user
is the value.
The alternative syntax is :factory => :user
. They mean the same thing.
Ruby 1.8 syntax:
:factory => :user
Ruby 1.9 syntax:
factory: :user
Note that the Ruby 1.8 syntax works in 1.9 also.
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