Ready to read all of the notes I have taken about Ruby on Rails so far? I hope so…
Back in 2005 when I was still an Economics major at Northwestern, I almost flunked out of my first quarter. I got hit hard. I had no idea what economics was, and that first Macroeconomics class I took completely overwhelmed me. It was boring, I didn’t get it, and it seemed like everyone around me did. Come to find out most people are introduced to economics later in high school, unfortunately I was not. I barely passed the class. The next quarter I took Microeconomics, and instead of giving up I decided to kick things up a notch. While I was in the midst of helping found my first start-up, I managed to do extremely well in the class. The way that I did so was I took all the notes and references and problem sets given in the class, I bought a rind of computer printing paper, and I rewrote everything expanding on them along the way on my computer paper. I remember one of my co-founders/mentors making a comment about my studying habits at one of our 4am studying sessions in Kellogg:
“You’re…diligent.”
I’m not sure whether that tactic is the most effective way to learn, but I didn’t know any other way to force the issue of learning. So I made it happen, and by the end of the quarter I was leading study sessions on topics and helping others with their Micro homework.
Fast forward to Ruby.
There’s a lot going on below. But I wanted to get everything I’ve written down out in the open, and perhaps update it and refine it over time. I’m sure someone will find some of this helpful!
The notes are divided in waves per some of the books I’ve read and what topics are being covered. I had links to most of the items I referenced but they didn’t transfer over to my text editor unfortunately. So if you don’t know what something is (especially the acronyms) google it and/or drop me a line asking about it!
Wave 0
Ruby:
- General purpose scripting language
- Strong, dynamic typing
- Started in Japan in 1994
- Inspired by Perl and Smalltalk
- Brought to the West by the Pickaxe book in 2000
LISP is a powerful language for metaprogramming – has a macro feature that will assign small keywords that will expand to represent larger blocks of code. LISP is one of the inspiration languages for Ruby as well.
BASIC – Beginners All-Purpose Symbolic Instruction Code – also inspiration for Ruby according to Matz.
Ruby on Rails:
- Full-stack MVC web application framework
- Extracted from 37signals Basecamp
- Convention over Configuration
– Our code is shorter than your XML file!
Database:
- Rails assumes a relational database
– Can actually work with non-relational ones if you make some changes
- The default is SQLite3
- The most commonly used are MySQL and PostgreSQL
There is also MongoDB, CouchDB and Redis.
- Ruby programs files end with “.rb”
Objects:
- In Ruby, everything is an object
- Programs consist of creating objects and sending messages to them (invoking methods) to perform work
– Method invocation in Ruby is nothing but a cover for sending a message to an object
Variables:
- Variables store references to objects to manipulate
- Lower-case and underscored name format
- Use “=” operator to assign a value
Exploring with IRB:
- IRB = Interactive Ruby
- Launch with irb command
- Lets you try out different Ruby commands with immediate feedback
Double quotes in Ruby enable string interpolation
Classes:
- A class is a blueprint that describes attributes and behavior of a particular type of object.
– Attributes are stored as instance variables
– Behavior is defined via methods, which can be invoked by sending messages to objects
- Objects are created (instantiated) from a class definition knows as a constructor…
Object is a concrete isntance of the design.
Anatomy of a class:
- Constructor
– Nothing but a built in method
- Instance variables (private)
- Instance methods
- Class variables (private): shared across all instances of a class
- Class methods: shared across all instances of a class
Defining Classes:
- Syntax
class ClassName
end
Methods:
- Methods represent available class behavior that can be performed…
Method Types:
- Instance methods
– Perform work focused on a class instance
Ex: update story estimate
– Dependant on data of a class instance
- Class methods:
– Perform work general to a class
– Ex: Get all stories from the repository
Invoking Methods:
- Syntax
– object.method_name([param1, [param2,] …])
- Examples of method invocations
– Instance method
– document.content
Class method
– Document.all_documents
- Unlike other languages
– May be invoked without ()
– Parameters are specified without types
DSL – Domain Specific Language – an API written in Ruby to simulate a language thats not ruby that you would use not using the Ruby syntax. Often it is an english-type description of what you are trying to do. Rspec is a DSL for example. Categorized by Martin Fowler, external DSLs = you’re defining a compeltely different language to make a task easier. Internal DSL are simulated within an existing syntax. Often drop parens to make it seem like an english statement. Rspec is internal and Cucumber is external. What is the purpose of the DSL? A: to make it easier for developers to accomplish certain tasks.
See here for more info:
http://stackoverflow.com/questions/899665/ruby-dsl-domain-specific-language-repositories-examples
Twibot, worth checking out:
http://cjohansen.no/en/ruby/twibot_a_microframework_for_twitter_bots_in_ruby
Constructors
- An object is constructed by invoking the “new” method of a class.
- Ex:
– states = Array.new
Exercise – Invoke Constructor
– Open story.rb and add the following lines at the botom:
– story = Story.new
– puts story.inspect
Every object in Ruby gets assigned an id.
Defining methods
- Instance methods
– def method_name(parameters)
do_some_work
end
- Class methods
– work the same way except you use self.blahblahblah
- Unlike other languages
– Operators can be methods too like: <<, >>, +, -, etc…
– Cannot use class methods…blahblahblah
Variable Types
- Variables come in different flavors
– local: belongs to block of code where it was declared
– example: x = 3
– instance: belongs to a class instance
– class: shared across all instances of a class
Instance Variabeles
– Name starts with @
– Example: @priority
– Accessible inside instance methods
– Each object getsits own instance variables
– Unlike local variables…
Class Variables
– Name starts with @@
– ex: @@default_priority
Accessible anywhere in a class
Typically initialized in a class body
…
Global Variables
– Name starts with $
– Ex: $ERROR_INFO
– Accessible anywhere in a Ruby application
– Usually store general data about Ruby
Getters and Setters
- Methods that focus on interacting with instance variables
- Getters access instance variables
- Setters modify instance variables
- Setter names may end with ‘=’
- Extra space before ‘=’ in method call is ignored by Ruby for convenience
Intializers
- Define “initialize” method to perform some work after an object is constructed
- Sometimes the “initialize” method is referred to as the constructor even though it is only responsible for initialization
Optional Parameters
- Methods may be passed optional
- Optional parameters are given a default value
- Syntax:
– def method_name(optional_parameter=default_value)
blah blah blah
end
Exercise 2 – Use Optional Parameters
- Update initializer in story.rb
Attributes
- Ruby attributes provide a shortcut to implementing getters and setters in a class
- Syntax
– Getters: attr_reader :attr1, :attr2, …
– Setters: attr_writer :attr1, :attr2, …
– Getters/Setters: attr_accessor :attr1, :attr2, …
attr_accessor is a class method.
require
- Syntax: require(file_name)
- Loads a Ruby file of not loaded before
- Takes the file name minus the .rb extension
- Specifies required dependency
- Ex:
– require ‘date’
– require ‘app/models/story’
Lookup – difference between load versus require
Rails uses load when you are in development mode so you can make changes without having restart the server. Once it is in production it uses require.
Require and Load
- The argument for require…blah blah blah
Inheritance
- An Object Oriented feature that allows classes to inherit data and behavior from other classes
- Helps in modeling the actual business domain
- Provides behavior and data reuse
- Eliminates confitional code that relies on object type checks
Look up – design patterns for object oriented programming.
Look up design pattern books for Ruby.
Look up – inheritance and mixins – cannot do multiple inheritance but you can use mixins instead.
Homework:
Ruby:
– Write a Ruby class that models an Iteration with the following attributes:
– Name (String)
– Start Date (Date)
– End Date (Date)
– In order to use Date you must use the date library by adding this on top:
– require ‘date’
Even regular expressions are objects in ruby.
See here http://www.marksanborn.net/howto/learning-regular-expressions-for-beginners-the-basics/
and here http://rubular.com/
Collections
- Arrays
– ordered
– index data by the natural number sequence
Hashes
– not ordered
– index data by object keys
Hashrockets is the way you map a key to a value (within a hash or an array) => – you do not use hashrockets with arrays because you cannot assign a key value pair.
Blocks and Procs
- A block is one or more Ruby statements surrounded by {} or do end.
- A block can receive parameters just like a method, allowing the encased statements do with them.
- Blocks do not have hashrockets
- A block is like an anonymous method that you can move around as an object
- Block paramaters are passed in pipes | |
- Any method in Ruby can optionally receive a block as its last parameter.
- When a block has one statement only, it is typically wrapped by {}
- Ex:
– { puts “hello” }
- When a block has multiple statements, it is wrapped by do end
- A proc is an object that encapsulates a block order to pass it around and execute it.
- Procs are created by calling the constructor and passing it a block
Iterators
- Iterators are methods that take a block to iterate over a collection and perform work on…
Iterators:
- each
- map
- inject
- each_with_index
- find
Exercise
- Create a program that takes an input from the keyboard (using ‘gets’) and prints each character on a new line.
Input Output
Hi Mom H
i
M
o
m
yield keyword
- Redirects execution to the block the caller gave us
- Any method can contain…
Modules
- Have two roles
– Mixins
– Namespaces
- Cannot be instantiated
Modules have the same conventions as classes.
Super also works for modules in addition to super classes.
Modules as namespaces
- Used to prevent name clashes
- Consists of nested modules and classes
- Use :: to reference nested modules/classes
- Example:
– Test::Unit::TestCase
Look this up – http://en.wikipedia.org/wiki/Namespace
Constants
- Constants declared in a particular context are:
– Visible in enclosed contexts
– Visible anywhere if nesting path specified
Flow control
- Conditional execution – if else elsif unless case
- Statement modifiers
- Looping – loop, while, until, for(typically not used each is used instead for arrays)
Exceptions
- Instances of the class Exception
- Interrupt normal execution
- Raised when problems occur
- Keywords: begin, rescue, ensure, raise
Global scope
- Applies to global variables (e.g. $time)
- Ensures variable is visible everywhere
Local scope
- Applies to local variables (e.g. total)
- Ensures visibility in a particular context
- Local scopes…
self
- Ruby keyword for the current objext
- There is only one self at any given moment
- There is only one self per context
Where am I?
- Top level => main object
- Class definition => the class
- Module definition => the module
- Class definition => the class
- Instance => instance method…
Singleton class
- Same rules apply to a singleton class and instance methods
- Do not confuse with Singleton design pattern
self often optional…
Name collision
- If method and variable names collide, the variable wins
Method access
Access levels
- Public (default)
- Private – only visible to the instance or inheriting instance that owns method
- Protected (rarely used)
Wave 1
MVC
Setting up a test directory with Rspec (whose syntax is a Domain-Specific language) and Webrat
Ruby Gems
Deploying the app to Git (via Github) and Heroku (regularly)
Git flags – like -a for “all changes” and -m for “message”
Get – the most common HTTP operation, used for reading data on the web; it just means “get a page”, and every time you visit a site like google.com or craigslist.org your browser is submitting a GET request
Post – the next most common operation; it is the request sent by your browser when you submit a form. In Rails applications, POST requests are typically used for creating things (although HTTP also allows POST to perform updates); for example, the POST request sent when you submit a registration form creates a new user on the remote site.
Put/Delete – designed for updating and destroying things on the remote server. These requests are less common than GET and POST since browsers are incapable of sending them natively, but some web frameworks (including Ruby on Rails) have clever ways of making it seem like browsers are issuing such requests.
Static HTML pages upon creation of a new rails app – automatically generating them
config/routes.rb – the file Rails uses to find the correspondence between URLs and web pages
classes and functions(methods)
hashes and symbols
how classes inherit from the parent (i.e. ApplicationController)
Test Driven Development (TDD) – “there should be an about page”, making sure the tests fail first so you know when you actually implemented the feature when it passes,
“Red, Green, Refactor” – Red – writing a failing test. Green – passing test. Refactor – Changing the form (eliminating duplication) without changing the function.
Autotest (I had trouble setting this up last go around in the summer)
Growl – very handy for a bunch of mac apps, but for this it’s useful for Autotest notifications
HTTP status- 200 means “success” 301 means “permanent redirect”
curl
Extreme Programming
Spork
drb
“smelly code” – gets ugly, bloated, or filled with repetition
Ruby doesn’t care about newlines (but we do!)
DRY
instance variables (linking actions and views) and assignments
ERb (Embedded Ruby)
Haml (awesome)
Sass (even more awesome)
CSRF
concatenation
Wave 2
If you are going to be a rails developer it could be helpful to learn rails first and pick up ruby along the way as opposed to starting off with pure ruby
http://www.blueprintcss.org/
https://github.com/joshuaclayton/blueprint-css/wiki/quick-start-tutorial
Unix commands: cp and -r
rails c – shortcut for rails console
rails s – shortcut for rails server
foo, FUBAR – http://www.catb.org/jargon/html/F/foo.html
~ is home directory in terminal
interactive Ruby (irb)
API
puts (said like “put ess”) – most commonly used ruby function to print a string
modules, comments, local variable assignment, booleans, control flow, string interpolation, and return values
nil – Ruby speak for “nothing at all”
Ruby supports single and double quoted strings – but won’t interpolate into single-quoted strings – single quotes are important because they are truly literal – meaning the strings will contain exactly what you type
“Newlines (\\n) and tabs (\\t) both use the backslash character \\.” ‘Newlines (\n) and tabs (\t) both use the backslash character \.’
Development, tst, and Production environments
boolean – true or false – good for control flow, can be combined using && for “and” || for “or” and ! for “not” operators
instance variables – variables with an @ sign – better understood by contrasting with ordinary variables – undefined local variables will start an argument with Ruby, but if you use an instance variable Ruby won’t argue because they are nil if not defined.
the nil object is special, it’s the only Ruby object that is false in a boolean context apart from ‘false’ itself – which means all other Ruby objects are true
Ruby functions have an implicit return – they return the last statement evaluated
Process: define method (function definition), assign variable, establish a boolean test (for nil, for example), establish implicit return (control flow), and the string interpolation
code in Ruby modules can be mixed in to Ruby classes (like module ApplicationHelper) – rails does something with this that makes it include itself explicitly without having to do it yourself automagically
array – list of elements in a particular order
the ‘split’ method divides a string into an array by splitting on whitespace, but you can also use anything else to split it with if you like
Ruby arrays are zero-offset – the first element in the array has index 0, the second has index 1, and so on
equality comparison operator ==
not equal operator !=
you can add to arrays with the “push” operator <<
you can also << chain << pushes << together
closely related to arrays are ranges - useful for pulling out array elements like 0..9
both arrays and ranges respond to a host of methods that accept blocks
blocks - { |character| function } Ruby syntax for a block variable - it's up to the method to know what to do with the block - curly braces are one way to indicate a block
blocks are closures - one-shot anonymous functions with data attached
%w makes string arrays
do..end syntax for blocks is used for multiple line blocks whereas curly braces can be used to define one line blocks
there is no shortcut to understanding blocks - you just have to see them a lot and eventually you'll get used to them
Everything in Ruby is an object. Objects respond to messages. Messages that get passed to objects are typically methods. Methods are functions defined on those objects. Functions and methods are the same in Ruby. All methods are functions and all functions are methods because everything in Ruby is an object.
hashes - a generalization of arrays - think of them as arrays but not limited to integer indices - hash indices aka keys can be almost any object - so if we have user = {} the {} is the empty hash and user is the key representing that hash, once the hash is defined within the brackets inputting user in the Ruby console would output its literal representation - curly braces for hashes have nothing to do with curly braces for blocks - even though they resemble each other the important difference is that hashes don't generally guarantee keeping their elements in a particular order - if order matters you should use an array
methods
Strings - the most important data structure for web applications, since web pages ultimately consist of strings of characters sent from the server to the browser
strings can be used as hash keys, but in rails it's more common to use symbols instead - symbols kind of look like strings but they are prefixed with a colon instead of surrounded by quotes (for ex :name) - symbols are essentially strings without the extra baggage - as a result of this they are easier to compare to each other - strings need to be compared character by character while symbols can be compared all in one go which makes them ideal for use as hash keys
built-in Rails methods, method invocation with missing parentheses, symbols, and hashes
hash values can be virtually anything, even other hashes - these are called nested hashes (hashes of hashes) which are used heavily in rails
hashes - similar to arrays and ranges - respond to the each method - the each method for arrays takes only one variable whereas the each method for hashes takes two - a key and a value - so the each method for a hash iterates through the has one key-value pair at a time
using inspect to print an object is common enough that there's a shortcut p for it - the inspect method returns a string with a literal representation of the object it's called on
parentheses on function calls are optional: stylesheet_link_tag('blueprint/screen', :media => ‘screen’) and stylesheet_link_tag ‘blueprint/screen’, :media => ‘screen’ are the same
Ruby uses classes to organize methods – the classes are then instantiated (the process of creating either a new object or a new instance of a class) to create objects.
Class Inheritance – Hierarchy for the String class: String inherits Object. Object Inherits BasicObject. Superclass of String is Object, Superclass of Object is BasicObject – this pattern is true for every Ruby object – if you trace back the class hierarchy far enough and every class in Ruby ultimately inherits from BasicObject which has no superclass. This is what it means when it is said that everything in Ruby is an object.
< is the ruby syntax for inheritance - ex: Word < String
Ruby classes can be opened and modified to add new or different methods to them
deified is a palindrome
Rails is sui generis and should be studied and understood separately from Ruby
Wave 3
You can style your code using partials
mockups and wireframes are essentially the same thing
divisions are divs
Internet explorer sucks
Yeah it really sucks because you have to use conditional comments to clue it in
CSS is very forgiving
container division – container div – is a div tag with class container – needed by blueprint css
header and section are elements
The div tag in HTML is a generic division; it doesn’t do anything apart from divide the document into distinct parts
In older style HTML, div tags are used for nearly all site divisions but HTML5 adds header, nav, and section elements for divisions common to many applications – which can all be assigned classes and ids
main difference between classes and ids – classes can be used multiple times on a page, ids can only be used once
rails helper: image_tag – Rails/Ruby <%= image_tag("logo.png", :alt => “Sample App”, :class => “round”) %> – produces in HTML5
Rails/Ruby – note that the img tag is self closing – meaning it doesn’t need an end tag
another rails helper: link_to (to insert links from erb html)
the stub URL placeholder ‘#’ is commonly used in web design practices
CSS elements are semantic – they have meaning in English beyond the structure of the page
CSS comments – /*…*/ – helpful to comment out pieces of code to see what changes
rails helper: render – as in <%= render 'layouts/stylesheets' %>
<%= ... %> is the Embedded Ruby syntax needed to evaluate a Ruby expression and then insert the results into the template
integration tests – gives us a way to simulate a browser accessing our application and thereby test it from end to end
Wave 4
The first step for modeling and viewing users is to create a data model for the users of the site together with a way to store that data
Rails-based authentication systems are out there – Clearance, Authlogic, Devise, and CanCan
Why you should start by building your own authentication system – Authentication systems are a challenging and rich programming exercise; rolling our own means that we can consider one small piece at a time, leading to a far deeper understanding—of both authentication and of Rails.
the first step in signing up users is to make a data structure to capture and store their information
the default data structure for a model is called a model (the M from MVC)
the default solution to the problem of persistence is to use a database for long-term data storage, and the default library for interacting with the database is called Active Record
Active Record comes with a host of methods for creating, saving, and finding data objects, all without having the use the structured query language (SWL) used by relational databases
Rails has a feature called migrations to allow data definitions to be written in pure Ruby, without having to learn a SQL definition language (DDL). Rails insulates you almost entirely from the data store.
In case you ever do need to write database-specific code to deploy on Heroku, know that they use PostgreSQL (“post-gres-cue-ell”) database. PostgreSQL is free, open-source, and cross-platform; if you develop PostgreSQL-specific applications, you can install it locally, and configure Rails to use it in development by editing the config/database.yml file
to store data Rails uses a relational database by default, which consists of tables composed of data rows, where each row has columns of data attributes
in contrast to the plural convention for controller names, model names are singular: a Users controller, but a User model
Migrations provide a way to alter the structure of the database incrementally, so that our data model can adapt to changing requirements
By using an email address as the username, we open the theoretical possibility of communicating with our users at a future date
run the migration, known as “migrating up”, using the rake command – $ rake db:migrate
see the structure of the database http://sqlitebrowser.sourceforge.net/
if you realize there’s another column you want to add but don’t want the trouble of making a new migration: you can roll back the migration, add the desired column, and then migrate back up – $ rake db:rollback
thesyntaxclass User < ActiveRecord::BasemeansthattheUser class inherits from ActiveRecord::Base, so that the User model automatically has all the functionality of the ActiveRecord::Base class
annotate gem - a command called annotate, which simply adds comments containing the data model to the model file
Tell Rails which attributes of the model are accessible, i.e., which attributes can be modified by outside users (such as users submitting requests with web browsers). Do this with the attr_accessible method
start the console in a sandbox: $ rails console --sandbox - Any modifications you make will be rolled back on exit - keep an eye on the development log, which records the actual low-level SQL statements being issued by Active Record - The way to get this output at a Unix command line is to tail the log: $ tail -f log/development.log - The -f flag ensures that tail will display additional lines as they are written - keep an open terminal window for tailing the log whenever working at the console
calling User.new doesn’t touch the database; it simply creates a new Ruby object in memory. To save the user object to the database, we call the save method on the user variable
timestampsarerecordedinCoordi- nated Universal Time (UTC), which for most practical purposes is the same as Greenwich Mean Time
The inverse of create is destroy
once you have defined some attributes as accessible using attr_accessible, only those attributes can be modified using update_attributes. If you ever find that your models mysteriously start refusing to update certain columns, check to make sure that those columns are included in the call to attr_accessible.
we shouldn’t allow name and email to be just any strings; we should enforce certain constraints on their values. Active Record allows us to impose such constraints using validations - the most common cases, validating presence, length, format and uniqueness
$ rake db:test:prepare - ensures that the data model from the development database, db/development.sqlite3, is reflected in the test database, db/test.sqlite3
being meticulous about TDD is simply the only way to be confident that we’re testing the right thing
the comment-out technique is also useful when rescuing an application whose application code is already written but has no tests
curly braces are optional when passing hashes as the final argument in a method
the use of validates is a characteristic of Rails 3. (In Rails 2.3, we would write validates_presence_of :name instead.)
The application code for email format validation uses a regular expression (or regex) to define the format, along with the :format argument to the validates method
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
coolness http://www.rubular.com/
to filter orders from Amazon, you can use username+amazon@gmail.com, which will go to the Gmail address username@gmail.com, allowing you to filter on the string amazon
Rails tests are transactional: each test is wrapped in a transaction, which rolls back the database after the test executes. This way, each test runs against a fresh database.
Using validates :uniqueness doesnotguaranteeuniqueness.
Rails comes equipped with three environments: test, development, and production. The default environment for the Rails console is development
Rails debug information is shown as YAML (a recursive acronym standing for “YAML Ain’t Markup Language”), which is a friendly data format designed to be both machine- and human-readable
Wave 5
Rails consoles started in a sandbox locks the database and prevents the migration from going through
callback – a method that gets invoked at a particular point in the lifetime of an Active Record object
pri- vate keyword; inside a Ruby class, all methods defined after private are used internally by the object and are not intended for public use
any web developer worth his salt should know how to implement a password system with secure one-way hashing
encrypted passwords – rather than storing a raw password in the database (known as “cleartext”), we store a string generated using a cryptographic hash function, which is essentially irreversible, so that even an attacker in possession of the hashed password will be unable to infer the original
Rainbow attacks – http://en.wikipedia.org/wiki/Rainbow_attack
Salt – http://en.wikipedia.org/wiki/Salt_(cryptography)
a class method is simply a method attached to a class, rather than an instance of that class. For example, new, find, and find_by_email are all class methods on the User class. Outside of the class, they are invoked using the class name, as in User.find, but inside the class we can omit the class name
Inside of an ordinary method, self refers to an instance of the class, that is, the object itself
Inside the encrypt_password method, self is a user object, so self.salt is the same as user.salt outside the method
unlike the tests for the new action, the tests for the show action will require the use of an instance of the User model
user factory – a convenient way to define a user object and insert it into our test database
FACTORY GIRL – https://github.com/thoughtbot/factory_girl
THESE THOUGHTBOT GUYS ARE AWESOME – http://thoughtbot.com/community/ – I know you all don’t understand the value of most of these projects, but the fact that I am starting to understand is a dramatic upgrade in my learning – peep the “Flutie” project with the awesome logo
Cross site scripting attack – http://en.wikipedia.org/wiki/Cross-site_scripting
Gravatar – http://en.gravatar.com/ – Rails sees you…
More on Gravatars – In Hinduism, an avatar is the manifestation of a deity in human or animal form. By extension, the term avatar is commonly used to mean some kind of personal representation, especially in a virtual environment.
Rails makes all helpers available in all views
If anyone gives you grief for using, horror of horrors, tables for layout, have them point their Firebug inspector at Twitter’s profile sidebar and tell you what they see – sometimes getting the vertical alignment just right is much easier with tables
Wave 6
The HTML element needed for submitting information to a remote website is a form – accomplish this in Rails with the form_for helper method
form_for now uses the “percent-equals” ERb syntax for inserting content; that is, where Rails 2.x used <% form_for ... %>, Rails3uses <%= form_for ... %> instead
what the f object does: when called with a method corresponding to an HTML form element—such as a text field, radio button, or password field—it returns code for that element specifically designed to set an attribute of the @user object
name values allow Rails to construct an initialization hash (via the params variable) for creating users using the values entered by the user
Rails creates the form tag using the @user object: because every Ruby object knows its own class, Rails figures out that @user is of class User; and since @user is a new user, Rails knows to construct a form with the post method, which is the proper verb for creating a new object
action=”/users” and method=- “post”. – constitute instructions to issue an HTML POST request to the /users
Rails authenticity token – http://stackoverflow.com/questions/941594/understand-rails-authenticity-token
resources :users to the routes.rb file automatically ensures that our Rails application responds to the RESTful URLs – it ensures that a POST request to /users is handled by the create action
RSpec count method is used to return the number of users in the database
Ruby construct lambda – allows us to check that it doesn’t change the User count
render works in controller actions as well
if-else branching structure – allows us to handle the cases of failure and success separately based on the value of @user.save
params hash contains information about each request; in the case of a URL like /users/1, the value of params[:id] is the id of the corresponding user
In the case of posting to the signup form, params instead contains a hash of hashes
the value of
with name “user[email]” is precisely the email attribute of the user hash
the hash keys appears as strings in the debug output, internally Rails uses symbols, so that params[:user] is the hash of user attributes—exactly the attributes needed as an argument to User.new
@user = User.new(params[:user]) is equivalent to @user = User.new(:name => “Foo Bar”, :email => “foo@invalid”, :password => “dude”, :password_confirmation => “dude”) – This is exactly the format needed to initialize a User model object with the given attributes.
form_for automatically fills in the fields with the attributes of the @user object
it’s helpful to output error messages on failed signup to indicate the problems that prevented successful user registration. Rails provides these messages based on the User model validations
To display the messages in the browser, render an error-messages partial on the user new page – Before Rails 3, displaying error messages was done through a magical call to a special error_messages method on the form object f, asfollows:<%= f.error_messages %>.Though often convenient,this magical method was hard to customize,so the Rails Core team decided to recommend using Embedded Ruby to display the errors by hand
a common Rails convention is to put partials we expect to be used from multiple controllers in a dedicated shared/ directory
the empty? method, in addition to strings, also works on arrays, returning true for an empty array and false otherwise
The any? method is just the opposite of empty?, returning true if there are any elements in the array and false otherwise.
pluralize takes an integer argument and then returns the number with a properly pluralized version of its second argument. Underlying this method is a powerful inflector that knows how to pluralize a large number of words (including many with irregular plurals)
the CSS id error_explanation is used in styling the error messages
on error pages Rails automatically wraps the fields with errors in divs with the CSS class field_with_errors. These labels then allow us to style the error messages with the CSS
cleartext – http://www.computerhope.com/jargon/c/cleartex.htm
If you ever write a Rails application with a secure parameter with a name other than password, you will need to add it to the array of filtered parameters
Special variable called the flash, which operates like flash memory in that it stores its data temporarily. The flash variable is effectively a hash
the key :success is a symbol, but Embedded Ruby automatically converts it to the string “success” before inserting it into the template
The reason we iterate through all possible key/value pairs is so that we can include other kinds of flash messages
“equals-tilde” =~ operator for comparing strings to regular expressions
regular expressions are case-sensitive by default, but we can be more permissive in the match using /…/i to force a case-insensitive match
green styling for the success class comes included with the Blueprint CSS framework
have a test for the entire signup process: visiting the signup page, filling in the form values, clicking the button, and making sure (if the submission is valid) that a new user gets created in the (test) database
cucumber as an alternative for testing https://github.com/aslakhellesoy/cucumber/wiki/tutorials-and-related-blog-posts
Webrat was written before the widespread adoption of Rack and will eventually be supplanted by the Capybara project. Capybara is designed as a drop-in replacement for Webrat, so the syntax should remain the same.
Wave 7
A session is a semi-permanent connection between two computers, such as a client computer running a web browser and a server running Rails. There are several different models for session behavior common on the web: “forgetting” the session on browser close, using an optional “remember me” checkbox for persistent sessions, and remembering sessions until the user explicitly signs out. – http://en.wikipedia.org/wiki/Session_(computer_science)
Unlike the case of the Users controller, which uses a database back-end (via the User model) to persist data, the Sessions controller will use a cookie, which is a small piece of text placed on the user’s browser.
flash and flash.now. The flash variable is designed to be used before a redirect, and it persists on the resulting page for one request—that is, it appears once, and disappears when you click on another link. Unfortunately, this means that if we don’t redirect, and instead simply render a page, the flash message persists for two requests: it appears on the rendered page but is still waiting for a “redirect” (i.e., a second request), and thus appears again if you click a link. To avoid this weird behavior, when rendering rather than redirecting we use flash.now instead of flash. The flash.now object is specifically designed for displaying flash messages on rendered pages. If you ever find yourself wondering why a flash message is showing up where you don’t expect it, chances are good that you need to replace flash with flash.now.
Ruby provides a module facility for packaging functions together and including them in multiple places
By default, all the helpers are available in the views but not in the controllers.
We can use cookies as if it were a hash; each element in the cookie is itself a hash of two elements, a value and an optional expires date
the flexibility to add methods to built-in classes allows for extraordinarily natural additions to plain Ruby, much of the elegance of Rails ultimately derives from the malleability of
the underlying Ruby language.
There are 10 kinds of people in the world: Those who like the ternary operator, those who don’t, and those who don’t know about it.
Web browsers can’t actually issue DELETE requests; Rails fakes it with JavaScript
we can use symbols in place of strings for the labels ,e.g., fill_in :email instead of fill_in “Email”
we can link directly to a user object and allow Rails to figure out the appropriate URL