Archive

Archive for October, 2009

Assignment 4 download available

October 31st, 2009 john No comments

For those of you who burn the midnight oil, as I do . . .

The download for Assignment 4 (and 5) is available on the downloads page. I’ll send an e-mail tomorrow morning (the Harvard e-mail service is unavailable from 1 AM to 4 AM!!).

Categories: Announcements Tags:

What gets validated?

October 26th, 2009 Antony No comments

Say you have a model called Match with attributes wins and losses, both of type integer.  To this model you add validation to ensure these attributes are only integers:

class Match < ActiveRecord::Base
 validates_numericality_of :wins, :only_integer => true
 validates_numericality_of :losses, :only_integer => true
end

Then, in script/console:

>> m = Match.new
=> #<Match id: nil, wins: nil, losses: nil, created_at: nil, updated_at: nil>
>> m.wins = "seven"
=> "seven"
>> m.losses = "five"
=> "five"
>> m
=> #<Match id: nil, wins: 0, losses: 0, created_at: nil, updated_at: nil>
>> m.valid?
=> false

The strings have been cast as integers, but why does the validation fail?  The answer is that ActiveRecord stores much more information than what shows up as instance attributes.

>> m.attributes_before_type_cast
=> {"created_at"=>nil, "losses"=>"five", "updated_at"=>nil, "wins"=>"seven"}

An indepth look at all of the machinery of ActiveRecord might be a course in itself, but I thought this would provide a taste of the breadth and depth of the ORM.

Categories: Announcements Tags:

Migrating existing data

October 26th, 2009 Antony 2 comments

Agile Web Development with Rails, 17.4 and 17.5, covers this subject.

On page 307 of the PDF, Migrating Data with Migrations, the basic scheme you might use is demonstrated.  As another example, suppose I create a users table and model:

$ ./script/generate model users first_name:string last_name:string

The migration looks like this:

class CreateUsers < ActiveRecord::Migration
 def self.up
   create_table :users do |t|
     t.string :first_name
     t.string :last_name

     t.timestamps
   end
 end

 def self.down
   drop_table :users
 end
end

After adding a number of users, it becomes clear that a full_name attribute would be very useful:

$ ./script/generate migration AddFullNameToUser full_name:string

This new migrations looks like this:

class AddFullNameToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :full_name, :string
  end

  def self.down
    remove_column :users, :full_name
  end
end

Before running it, I add the line to update the users:

class AddFullNameToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :full_name, :string
    User.find(:all).each do |u|
      u.full_name = u.first_name + ' ' + u.last_name
      u.save!
    end
  end

  def self.down
    remove_column :users, :full_name
  end
end

An important note here:  I did not use update_all because string concatenation is not portable between database engines (|| for Oracle, postgres and sqlite3, + for SQL Server and Sybase,  concat for MySQL, etc).

As John demonstrated in his migrations 3 example, depending on what you are trying to accomplish, the down method may not be data preserving.

Beyond the above and similar data manipulation, section 17.5 covers ways to execute fragments of native SQL or arbitrary SQL.  Using this functionality is beyond the scope of this course and of course has the significant downside of being much less portable.

Categories: Announcements Tags:

gem of the week: cheat

October 13th, 2009 john No comments

A couple of weeks ago I mentioned the “cheat” gem which has a plethora of useful quick docs on various topics such as regular expressions. I breezed through the install — and fix for Ruby 1.9.1 — here it is, for the record:

gem install cheat
# NOTE: If you're on Linux or OS/X and have a standard install (rather than using the ruby_switch.sh script, you want to do sudo gem install cheat)

If you run it under 1.9.x, you should get an error like so:

cheat regexp
/Users/jnorman/.gem/ruby/1.9.1/gems/cheat-1.2.1/lib/cheat.rb:150:in `cache_dir': uninitialized constant Cheat::PLATFORM (NameError)
	from /Users/jnorman/.gem/ruby/1.9.1/gems/cheat-1.2.1/lib/cheat.rb:16:in `sheets'
	from /Users/jnorman/.gem/ruby/1.9.1/gems/cheat-1.2.1/bin/cheat:4:in `<top (required)>'
	from /Users/jnorman/.gem/ruby/1.9.1/bin/cheat:19:in `load'
	from /Users/jnorman/.gem/ruby/1.9.1/bin/cheat:19:in `<main>'

What you want to do is edit the file producing the error (in my case, from the exception trace, /Users/jnorman/.gem/ruby/1.9.1/gems/cheat-1.2.1/lib/cheat.rb). Go to the line, and change the constant PLATFORM to RUBY_PLATFORM. Save the file.

And voila!

chelsea:~ jnorman$ cheat regexp
regexp:
  A regexp's form is written /pattern/modifiers where "pattern" is the regular
# much deleted

For help,

cheat cheat
Categories: Ruby, gems Tags:

Keeping projects small, code brevity

October 13th, 2009 john 2 comments

I know a number of you are interested in how Ruby and Rails seems to favor smaller projects, code brevity, and a general attitude of representational efficiency.

You might be interested in this new post by Ola Bini who discusses the claim that if a project is very big, you need all of the helps from a statically-typed language (such as Java).

http://olabini.com/blog/2009/10/plan-to-write-big-software-and-you-have-already-lost/

Categories: Ruby Tags:

Additional Standalone ActiveRecord Example

October 11th, 2009 Jonathan No comments

In the Sunday section, we re-created the previous example application using ActiveRecord. This is very similar to the examples from Lecture 6 in the download section, except that this was written with an emphasis on test driven development.

It includes examples of:

  • Migrations
  • Simple Seed Data
  • Fancy Finders
  • Validations and Validation Testing
  • One to Many Relationships

For the sake of time, there were no many to many relationships. Examples of m2m can be found in the download section.

Use rake -T to view the rake tasks. Use “rake db:migrate” to run the migrations, and “rake test” to run the tests.

Run “ruby section.rb” to run the demo code. Modify section.rb to play around with the finished results.

You can click here to download the complete source code.

Categories: Announcements Tags:

Command line sqlite

October 10th, 2009 Antony 6 comments

Execute the command sqlite3 at the command prompt passing the file name of the database:

$ sqlite3 <database name>.sqlite3

You should see output similar to the following:

SQLite version 3.6.10
Enter “.help” for instructions
Enter SQL statements terminated with a “;”
sqlite>

Check that the version is correct.  People running sqlite3 in emacs may need to set sql-sqlite-program.

Enter ‘.help’ to see the list of commands that provide information or set options. Input starting with a ‘.’ (period) signals non-SQL and should be one of those commands.  All other input will be interpreted as SQL and should be terminated with a ‘;’ (semi-colon).

Enter ‘.quit’ to exit.  Some other commands you will likely find useful are ‘.headers’, ‘.tables’, and ‘.schema’.

When using rails with sqlite3, this same functionality can be started with ’script/dbconsole’.

Categories: Announcements Tags:

Best Books on Rails

October 7th, 2009 john No comments

Compared to Ruby, the pickings are slim for great books that try to explain core Rails from end-to-end. Generally, each good book on Rails approaches a part of the Rails elephant.

Here are the ones I recommend:

Ruby, Thomas, and Hansson, Agile Web Development with Rails, 3d ed. (Amazon). If you’re taking this course, you should own this already. AWDR touches all the bases, but still has sections that drive readers a little bit crazy. But . . . essential.

David Griffiths, Head First Rails (Amazon; Safari). If you’re a learn-by-doing person and have the time to work through a book, this is the one. The Head First books know a lot about triggering learning in your brain through exercises and pictures. I think this book is most worthwhile very early in your experience with Rails; afterwards it may feel redundant.

Eldon Alameda, Practical Rails Projects (Amazon). The examples in this book are real-world and slick. Almeda has a good way at demonstrating how quickly you can get stuff done with Rails, selected Gems, and Rails plugins. A lot of good stuff on integrating Ajax/JavaScript with Rails.

Brad Ediger, Advanced Rails (Amazon; Safari). The natural followup to AWDR for readers who really have to get it right. The best aspect of this book is that it dares to go into some depth on topics such as the database, security, and performance.

Dan Chak, Enterprise Rails (Amazon; Safari). The meat of this book is about leveraging the underlying power of your database, using features that are a bit out of the Rails mainstream (composite keys; views; triggers; etc.). The book also benefits from understanding from the get-go that your new shiny enterprise app should be exposing and consuming services (SOAP, REST).

Obie Fernandez, The Rails Way (Amazon; Safari). This book is a ginormous grab bag of real-world scar tissue on just about every Rails topic. Want to know how and when the Rails Class Loader runs? Check. Should RESTful resource be nested deeply? Check. What’s wrong with CookieStore? Check. To buy after completing two Rails applications.

Categories: Announcements, Resources Tags:

Best Books on Ruby

October 6th, 2009 john No comments

A student asked for a list of the best books on Ruby (other than the ones that are required for the course); now that the dust has settled on getting through one version of Ruby, it’s time to provide the list.

During our study of Rails I’ll provide a similar list. (For our study of Ruby, I think it’s best to have “one version of the truth” in the form of the Pickaxe; for Rails, you will likely appreciate other voices, so I will provide that list sooner rather than later.)

I’ll give a link to Amazon as well as a link to Harvard’s Safari subscription (when available).

Flanagan and Matsumoto, The Ruby Programming Language (Amazon; Safari; also, only $10 for the PDF through O’Reilly). This book focuses on the language definition and details. It is loaded with interesting examples. The only thing it lacks is a broad tutorial chapter; you pretty much have to know at least one language already to know what to look for in the organization. (There is an introductory bit showing some of Ruby’s benefits, but it’s playing to the choir.) The index occasionally leaves something to be desired (for example, the book has occasional intelligent thinks to say about Java vs. Ruby, but there is only one entry under Java in the index).

David A. Black, The Well-Grounded Rubyist (Amazon; Safari). This is the best “second” book on Ruby, to be read after Programming Ruby or The Ruby Programming Language. It helps you understand how Rubyists think, and is a joy to read.

Peter Cooper, Beginning Ruby (2d ed.; Amazon). A great alternative to the Pickaxe. In a lot of ways, this is more straightforward than the Pickaxe, and a bit more “real-world” in terms of its examples.

Hal Fulton, The Ruby Way (2d ed.; Amazon; Safari). This book is about Ruby, but is also a cookbook for Ruby strategies to accomplish basic and not-so-basic tasks. One of the best parts is section 1.5.4 “Rubyisms and Idioms.” This book is worth reading annually for experienced Rubyists.

Carlson and Richardson, Ruby Cookbook (Amazon; Safari). A classic O’Reilly collection of techniques, pointers, strategies, advice. I don’t use this much anymore, but when I first acquired it, I found much of great interest.

Brad Ediger, Advanced Rails (Amazon; Safari). While a Rails book, Chapters 1, “Foundational Techniques,” has one of the best sections on how Ruby classes, modules, and eigenclasses really work. Chapter 2 has wonderful brief essays called “Ruby You May Have Missed” and “How to Read Code.” Good stuff.

Categories: Resources Tags:

Download of Ruby 1.9 docs with Rails docs

October 2nd, 2009 john No comments

I know that Windows users are hampered because ri is not properly installed.

If you’d like a nicely-formatted download of Ruby and Rails docs, try http://railsapi.com/

You can customize what you want, and include other components, adding docs for, say, the popular Hpricot HTML/XML parsing library (and much else).

They package docs for Rails 2.3.4 (rather than 2.3.3, which we’re using) which should be fine.

For Rails, a student reminds me that you can run “gem server” in one window, and then browse to http://localhost:8808/ to see docs for all gems you’ve installed (but not the core/standard Ruby docs).

Categories: Announcements Tags: