A while ago I attending the http://owningrails.com. It was a fantastic course which de-mystified Rails by showing it’s not magic - it just sometimes uses Rubys syntax to hide how it works.
This is a bit of a brain-dump of what I learnt - but you should go on the course, well worth the money.
Ruby Method Syntactic Sugar
Because Ruby method calls will be called on self by default and brackets are not manditory, this means that the below statements are equivalent:
before_filter :authenticate! == HomeController.before_filter(:authenticate!)
Modules vs Classes
extendadds module functions at class levelincludeadd module functions at instance level@attributeis instance level variable, includes in this instance only@@attributeis a class level variable, included in subclasses
Put methods in ClassMethods module to put them on the parent class, not the current module.
If you need to call super in a module method, you need to subclass the parent so that methods aren’t overridden. By default, ruby will execute the first match.
binding is a private method for the class containing instance variables etc.
autoload :constant lazy-loads the module so may save memory.
Blocks and Lambdas
- Blocks are not objects,
Procsare - Lambdas checks the number of arguments when called. Lambdas don’t
- Everything is an object (except blocks…)
yieldcalls blocks. Same as&blockargument. Converts block toProcyieldexecutes codes in root context.&blockexecutes in that instance usinginstance_eval&blockconverts block to aProc.instance_evaltakesProc/Stringnot a block&method(:name)converts method to block
Rack
Rack is a protocol, it defines how a webserver talks to Rails and how Rails talks to the webserver
Conventions
Use _ to ingore that variable, i.e.
_, name = 'boring/important'.split('/')