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:
This is a method call, sure. But it’s not the
make_rottingmethod that is called. It’s thebefore_save(:make_rottingis its parameter). This is a so-called hook in ActiveRecord.before_savewill take a method name as a parameter and will dynamically call it when the moment comes.Here
ageis a method call, not a symbol. It could be written as:but the parentheses are optional. And lastly:
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):
You should read a good book on Ruby programming, instead of scraping pieces of knowledge from Stack Overflow posts. 🙂