Beruflich Dokumente
Kultur Dokumente
Administrivia
5um signup!! Lab 0 Self-diagnostic quiz on web page Hack sessions: Th 4-5, Fri 1-2
place, staffing TBA on webpage
Books
more or less required: Agile Web Development with Rails, 1st or 2nd ed. Programming Ruby (free, online at rubycentral.org/book) or The Ruby Way by Fulton
Review: MVC
Goal: separate organization of data (model) from UI & presentation (view) by introducing controller
mediates user actions requesting access to data presents data for rendering by the view
Review: C/C
If data model is called Student: model (Ruby class) is app/models/student.rb SQL table is students
table row = object instance columns = object attribute
QuickTime and a TIFF (Un compressed) decompres are neede d to see this picture.
SQL AUTO_INCREMENT function makes it easy to specify an integer primary key If using migrations to create tables (recommended), Rails takes care of creating an autoincrement primary key field called ID
class CreateStudents<ActiveRecord::Migration CREATE TABLE students ( id INT NOT NULL AUTO_INCREMENT, last_name VARCHAR(255), first_name VARCHAR(255), ucb_sid INT(11) DEFAULT 9999 ); def self.up create_table :students do |tbl| tbl.column :last_name, :string tbl.column :first_name, :string tbl.column :ucb_sid, :integer, :null=>false, :default=>9999 end end def self.down drop_table :students end end
Note, need to be in a shell that has PATH and environment variables set correctly See www.ruby-doc.org for more good documents
Naming conventions
ClassNames
class NewRubyProgrammer ... end
predicate_like_methods?
def is_faculty_member? ... end
dangerous_methods!
def brainwash_with_ruby! ... end
:symbols
favorite_framework = :rails
SOME_CONSTANTS or OtherConstants
result in warning if reassigned after init
in particular, things like implicit conversion on comparison are done by the class methods, not in the language (unlike, e.g., Perl)
Everything* is passed-by-reference
can use clone method to effect pass-by-value
*except Fixnums...
Defining methods
def foo(x); [x,x+1]; end def foo(x) [x,x+1] end def foo(x) return [x,x+1] end
Arrays
x = [3, 'a', "third", :blah, :last] x[0] => 3 x[-1] => :last x[-2] => :blah x[-3..-1] => ["third", :blah, :last] y = [1,2] y += [3,4] => [1,2,3,4] y << 5 => [1,2,3,4,5] y << [6,7] => [1,2,3,4,5,[6,7]]
Note! These are nearly all instance methods of Arraynot language operators!
Hashes
h = {"key" => 1, :value => "foo" } h.has_key?("key") => true h["not a key"] => nil (not an error!) h.delete(:value) => {"key" => 1 } h.merge( {:key2 => "3", "hi" => :blah} ) => {"key"=> 1, "key2" => 3, hi => :blah}
...got it?
end
REMEMBER!
a.b means: call method b on object a a is the receiver to which you send the method call, assuming a will respond to that method does not mean: b is an instance variable of a does not mean: a is some kind of structure of which b is a member Understanding this distinction will save you from much grief and confusion
QuickTime and a TIFF (Uncompressed) decompre ssor are neede d to see this picture.
i.e.: If it looks like a duck and walks like a duck => it responds to the same methods as a duck. Note, a module a class
but module methods can get mixed in to classes
Parens can be omitted from function calls if parsing is unambiguous x = foo(3, "no") x = foo 3, "no" Braces can be omitted from hash if parsing is unambiguous x = foo( {:a=>1,:b=>2}) x = foo(:a=>1,:b=>2)
easy way to do keyword arguments Caveat: passing immediates to a function that accepts multiple hashes as its arguments
Dynamically typed
Objects have types; variables dont very few operators in the language; most are defined as instance methods on objects
ActiveRecord accessors/mutators
default attr_accessor for each table column perform type-casting as needed can be overridden, virtualized, etc.
Constructors
Method named initialize, but invoked as new (at least) 3 ways to call it...
New != Create
Call s.save to write the object to the database
s.create(args) s.new(args); s.save s.update_attributes(hash) can be used to update attributes in
place
s.new_record? is true iff no underlying database row corresponds
to s
Find by conditions
Use ? for values from parameters. Rails will sanitize the SQL and prevent any SQL injection You will want to learn some minimal SQL syntax
You can also specify ordering and use arbitrary SQL operators:
# Using SQL conditions books = Book.find(:all, :conditions => [pub_date between ? and ?, params[:start_date], params[:end_date]], :order => pub_date DESC)
Find by conditions
Use ? to substitute in condition values
not mandatory, but a good idea!
Advanced Find
You can also specify limits and offsets, and oh so much more
books = Book.find(:all, :conditions => [pub_date between ? and ?, params[:start_date], params[:end_date]], :limit => 10, :offset => params[:page].to_i * 10)
:lock - Holds lock on the records (default: share lock) :select - Specifies columns for SELECT (default *) :group - (used with select) to group :readonly - load as read-only (object cant be saved) :include - Prefetches joined tables (try :include first;
more about this in Section 4) Note: use SQL-specific features at your own risk....
Caveat!
The result of a find-all operation mixes in
Enumerable
Enumerable defines methods find and find_all
Caveats for using self. => local variable, method, methodmissing so need self. even for mutators activerecord accessors/setters are lazy & memoized dymamic finders are never memoized!
Action View
A template for rendering views of the model that allows some code embedding
commonly RHTML; also RXML, HAML, RJS note...too much code breaks MVC separation convention: views for model foo are in app/views/foo/
But these form tags are generic...what about modelspecific form tags? In the RHTML template:
<%= text_field 'student', 'last_name' %>
Action Controller
Each incoming request instantiates a new Controller object with its own instance variables
Routing (Sec. 4) determines which method to call Parameter unmarshaling (from URL or form sub.) into params[] hash ...well, not really a hash...but responds to [], []=
Then we render...
Once logic is done, render the view
exactly one render permitted from controller method (1 HTTP request 1 response)
i.e, params[:student] is a hash :last_name=>string, :degree_expected=>date, etc. and can be assigned directly to model object instance helpers for dates and other complex types...magic
The Flash
Problem: Im about to redirect_to somewhere, but want to display a notice to the user yet that will be a different controller instance with all new instance variables Rails answer: flash[]
contents are passed to the next action, then cleared to this action: flash.now[:notice] visible to views as well as controller
Summary
ActiveRecord provides (somewhat-)databaseindependent object model over RDBMS ActionView supports display & input of model objects
facilitates reuse of templates via layouts & partials
ActionController dispatches user actions, manipulates models, sets up variables for views
declarative specifications capture common patterns for checking predicates before executing handlers
Lab 1
Create a simple 1-model RoR app with basic CRUD MVC
Create database Create the table using migrations Create scaffolding using generator
Find and fix a bug in the code provided to you :-o Hack sessions, forums will help