Monday, February 17, 2014

Learning Notes about Agile Web Development with Rails (3)

Basic Ruby programming language knowledge

1. Ruby Names

Local variables, method parameters, and method names should all start with
a lowercase letter or with an underscore: order, line_item, and xr2000 are all
valid. Instance variables begin with an “at” sign (@), such as @quantity and @product_id. The Ruby convention is to use underscores to separate words in a multiword method or variable name (so
line_item is preferable to lineItem).

Class names, module names, and constants must start with an uppercase
letter. By convention they use capitalization, rather than underscores, to dis-
tinguish the start of words within the name. Class names look like Object,
PurchaseOrder, and LineItem.

Rails uses symbols to identify things. In particular, it uses them as keys when
naming method parameters and looking things up in hashes.

2. Methods

You don’t need a semicolon at the end of a statement as long as you put each
statement on a separate line. Ruby comments start with a # character and
run to the end of the line. Indentation is not significant (but two-character
indentation is the de facto Ruby standard).

Ruby doesn’t use braces to delimit the bodies of compound statements and
definitions (such as methods and classes). Instead, you simply finish the body
with the keyword end. The keyword return is optional, and if not present, the
results of the last expression evaluated will be returned.

3. Strings

This previous example also showed some Ruby string objects. One way to cre-
ate a string object is to use string literals, which are sequences of characters
between single or double quotation marks. The difference between the two
forms is the amount of processing Ruby does on the string while constructing
the literal. In the single-quoted case, Ruby does very little. With a few excep-
tions, what you type into the single-quoted string literal becomes the string’s
value.

In the double-quoted case, Ruby does more work. First, it looks for substitu-
tions—sequences that start with a backslash character—and replaces them
with some binary value. The most common of these is \n, which is replaced
with a newline character. When you write a string containing a newline to the
console, the \n forces a line break.

Second, Ruby performs expression interpolation in double-quoted strings. In
the string, the sequence #{expression } is replaced by the value of expression.

4. Arrays and Hashes

Ruby’s arrays and hashes are indexed collections. Both store collections of
objects, accessible using a key. With arrays, the key is an integer, whereas
hashes support any object as a key. Both arrays and hashes grow as needed
to hold new elements. It’s more efficient to access array elements, but hashes
provide more flexibility. Any particular array or hash can hold objects of dif-
fering types; you can have an array containing an integer, a string, and a
floating-point number, for example.

You can create and initialize a new array object using an array literal—a set
of elements between square brackets. Given an array object, you can access
individual elements by supplying an index between square brackets, as the
next example shows. Ruby array indices start at zero.

In Rails, hashes typically use symbols as keys. Many Rails hashes have been
subtly modified so that you can use either a string or a symbol interchangeably
as a key when inserting and looking up values.

nil is an object, just like any other, that happens to represent
nothing. nil means false when used in conditional expressions.

5. Regular Expressions

A regular expression lets you specify a pattern of characters to be matched in
a string. In Ruby, you typically create a regular expression by writing /pattern/
or %r{pattern}.

6. Block

Code blocks are just chunks of code between braces or between do...end. A
common convention is that people use braces for single-line blocks and do/end
for multiline blocks.

A method can invoke an associated block one or more times using the Ruby
yield statement. You can think of yield as being something like a method call
that calls out to the block associated with the method containing the yield. 
You can pass values to the block by giving parameters to yield. 

7. Exceptions

Exceptions are objects (of class Exception or its subclasses). The raise method
causes an exception to be raised. This interrupts the normal flow through the
code. Instead, Ruby searches back through the call stack for code that says it
can handle this exception.

Both methods and blocks of code wrapped between begin and end keywords
intercept certain classes of exceptions using rescue clauses.

rescue clauses can be directly placed on the outermost level of a method defi-
nition without needing to enclose the contents in a begin/end block.

8. Modules

Modules are similar to classes in that they hold a collection of methods, con-
stants, and other module and class definitions. Unlike classes, you cannot
create objects based on modules.

Modules serve two purposes.
First, they act as a namespace, letting you define methods whose names will not
clash with those defined elsewhere.
Second, they allow you to share functionality between classes—if a class mixes in a
module, that module’s instance methods become available as if they had been
defined in the class. Multiple classes can mix in the same module, sharing the
module’s functionality without using inheritance. You can also mix multiple
modules into a single class.

Helper methods are an example of where Rails uses modules. Rails automat-
ically mixes these helper modules into the appropriate view templates.

9. YAML

YAML is a recursive acronym which stands for YAML Ain’t Markup Language.
In the context of Rails, YAML is used as a convenient way to define config-
uration of things such as databases, test data, and translations.

10. Marshaling Objects

Ruby can take an object and convert it into a stream of bytes that can be stored
outside the application. This process is called marshaling. This saved object
can later be read by another instance of the application (or by a totally separate
application), and a copy of the originally saved object can be reconstituted.

There are two potential issues when you use marshaling. First, some objects
cannot be dumped. If the objects to be dumped include bindings, procedure or
method objects, instances of class IO, singleton objects, or if you try to dump
anonymous classes or modules, a TypeError will be raised.
Second, when you load a marshaled object, Ruby needs to know the definition
of the class of that object (and of all the objects it contains).

Rails uses marshaling to store session data. If you rely on Rails to dynam-
ically load classes, it is possible that a particular class may not have been
defined at the point it reconstitutes session data. For that reason, you’ll use
the model declaration in your controller to list all models that are marshaled.
This preemptively loads the necessary classes to make marshaling work.

11. Ruby Idioms

1) lambda

The lambda operator converts a block into a object of type Proc. 

2) require File.dirname(__FILE__) + ’/../test_helper’

Ruby’s require method loads an external source file into our application.
This is used to include library code and classes that our application relies
on. In normal use, Ruby finds these files by searching in a list of direc-
tories, the LOAD_PATH.


No comments:

Post a Comment