ruby on rails, colon at back or front of variables
What i have understand so far is that
:variable
in ruby, is to say that this variable will not be able to change, which is similar to constant in other language.
I'm not sure if I understand that statement. In Ruby, constants start with an uppercase letter:
Foo = 1
Reassignment generates a warning:
Foo = 1Foo = 2 #=> warning: already initialized constant Foo
Variables start with a lowercase letter and reassignment doesn't cause a warning (they are supposed to change):
foo = 1foo = 2 # no warning
Symbols start with a colon:
:a_symbol:Uppercase_symbol:"i'm a symbol, too"
They often represent static values, e.g. :get
and :post
. Symbols are memory efficient, because they are created only once - the same symbol literal always returns the same object. Checking if two symbols are equal is a cheap operation.
Both
key:
andmethod:
(...) What does that this represent?
This is an alternate syntax for hashes. You can type it in IRB to see the result:
{ foo: 1, bar: 2 }#=> {:foo=>1, :bar=>2}
There are double colons inbetween variables? now I am guessing that
Blog:
is one variable, and:Application
is constant.
No, Blog
and Application
are both constants and ::
is the scope resolution operator. It can be used to access nested constants, e.g.:
module Foo class Bar BAZ = 123 endendFoo::Bar::BAZ #=> 123
Rails.application.config.session_store :cookie_store, key: '_blog_session'
session_store
is a method that takes two "Arguments":
(could also be session_store :cookie_store, { key: '_blog_session' }
)
Similarly for link_to "Delete", article, confirm: "Are you sure?", method: :delete
"Delete"
is a stringarticle
a variable{ confirm: '...', method: :delete }
hash whereconfirm:
,method:
and:delete
are Symbols again.
While Blog::Application
:: is basically a namespace resolution operator. A way for you to address the Application class in the Blog
module.
Hope this helps. Have a look at the documentation I referenced, it is explained rather nicely.
:presence => true
presence: true
In the bottom example, the colon is saying, “Hey, I am pointing from presence to true.