Inconsistent naming conventions in Rails are confusing me. It seems like the syntax is all over the place. Here are some examples:
Why are there commas in the migration below? And, why doesn't the keyword default
have a colon before it? What is this default
keyword, a method, or a variable, a symbol? What is that thing?:
add_column :zombies, :rotting, :boolean, default: false
Here is another example:
Why is age
not :age
(with a colon)? Why is make_rotting
called with a ":
" before it?
class Zombie < ActiveRecord::Base
before_save :make_rotting
def make_rotting
if age > 20
self.rotting = true
end
end
end
Ruby can be hard for Java and PHP people. :)
In Ruby, not everything is what it appears to be. Take this, for example:
before_save :make_rotting
This is a method call, sure. But it's not the make_rotting
method that is called. It's the before_save
(:make_rotting
is its parameter). This is a so-called hook in ActiveRecord. before_save
will take a method name as a parameter and will dynamically call it when the moment comes.
if age > 20
Here age
is a method call, not a symbol. It could be written as:
if age() > 20
but the parentheses are optional. And lastly:
add_column :zombies, :rotting, :boolean, default: false
This method takes four parameters, the last of which is a hash. The hash uses the new Ruby 1.9 syntax. Previously it would be written like this (with the colon in the right place, and all):
add_column :zombies, :rotting, :boolean, :default => false
You should read a good book on Ruby programming, instead of scraping pieces of knowledge from Stack Overflow posts. :)
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