Learning Ruby On Rails: Day 10
3 min readOct 29, 2018
In an attempt to learn more, faster, I’m changing the style of these posts a little. I’ll be sharing notes, rather than creating micro tutorials of what I’ve learned each day.
- Action Pack: the Controller and View Rails component.
- We generate dynamic content in our views with Embedded Ruby (
erb
). - Ruby is an object oriented programming language.
- Local variables, method names and method parameters should all start with a lower case letter or underscore.
- Instance variables begin with an
@
. - Use underscores to separate words.
- Class names are capitalized and CamelCased.
- Symbols are string literals magically made into constants.
- Everything in Ruby is an object.
- Double quotes are used for expression interpolation, and for strings that have single quotes in them. Example:
"Let's hang out"
. - Arrays are ordered collections of things. To reference an item in an array, you use an item’s index (which is an integer). Example:
array_of_things[0]
. - Hashes are collections of key/value pairs. To reference an item in a hash, you use its key (which can be a symbol or string). Example:
hash_of_things[:some_key]
. nil
is an object.- The
<<
method is used to append a single value to the end of an array. - Hashes have keys and values.
- The keys can be a symbol, string, or a variable that returns a symbol or string.
- The syntax to separate a key from its value is always a hashrocket (
=>
). - The one allowed exception to this rule is if the key is a symbol, in which case the symbol can be immediately followed (no space) by a colon. And then a space.
- That said, a symbol as a key is still allowed to use a hash rocket. (In which case the symbol’s colon goes at the start of the symbol, not the end.)
- The colon separator is completely optional and is syntactical sugar. (ie, it’s nice and cleaner, but not required.)
unless
is likeif
but it checks for the condition not to betrue
.until
is likewhile
, but it continues until the condition evaluates totrue
.- We can put the
if
/unless
at the end of a line of code instead of wrapping the line of code in anif
/unless
block. Like this:
puts “danger will Robinson” if radiation > 3000distance = distance * 1.2 while distance < 100
- Two organizations for methods:
classes
andmodules
.
Class Order < ApplicationRecord has_many :line_items def self.find_all_unpaid self.where(‘paid = 0’) end def total sum = 0 line_items.each {|li| sum += li.total} sum endend
In the above code snippet:
Order
inherits all behavior fromApplicationRecord
.has_many
is a method defined byActiveRecord
. It is called as theOrder
class is being defined.- Prefixing a method with self makes it a class method. So it can be called anywhere on the class, instead of on an instance of that class.
- So I could write:
to_collect = Order.find_all_unpaid
instead of:@order = Order.new
and then:@order.find_all_unpaid
.
Bai!
Next post, here.