Aug 1 10

Basecamp notes from DHH

by Dave

1.
First focus on your writing. Simplicity.
Have good human writing. Nobodies impressed by big words.

2. Planning 5 years out is guessing
wastes your time and sucks your energy.

3.
Decisions are temporary.
What matters most is starting.
Just do something.

4. Have constraints! Set them yourself!
Forces you to make decisions and get things done.
Not waste time.
A sense of urgency.

Spending and earning your own money is a powerful driving force!

5.
10 hours per week, 6 months.

6.
It doesn’t work to go head to head with someone who has more than you!
So you have to do something different.
Fewer features. Under-do your competition.

7.
No overnight successes.

May 23 10

Working with Models

by Dave

Models

In Rails, the default data structure for a data model is called, naturally enough, a model (the M in MVC) . The default Rails 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.1
Active Record comes with a host of methods for creating, saving, and finding data objects, all without having to use the structured query language (SQL) used by relational databases. Moreover, Rails has a feature called migrations to allow data definitions to be written in pure Ruby, without having to learn an SQL data definition language (DDL). The effect is that Rails insulates you almost entirely from the details of the data store.

Create the model

$ script/generate rspec_model User name:string email:string

Migrate “up” using

$ rake db:migrate

Roll back (down) using

$ rake db:rollback

Model annotation

Though it’s not strictly necessary, I like to annotate my Rails models using the annotate models plugin:

$ script/plugin install \
> http://repo.pragprog.com/svn/Public/plugins/annotate_models
$ rake annotate_models

This will cause your model files to look like the following:

# == Schema Information
# Schema version:
# Table name:
# id :integer  not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime
# updated_at :datetime
#

class User < ActiveRecord::Base
end

After adding any plugins, remember to commit to Git

$ git add .
$ git commit -am "Annotated models"

Accessible attributes
Another step that isn’t strictly necessary but is a really good idea is to 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). We do this with the attr accessible method. Using attr accessible is important for preventing a mass assignment vulnerability, a distressingly common and often serious security hole in many Rails applications.

class User < ActiveRecord::Base
  attr_accessible :name, :email
end

Searching models

User.find(1)  # where 1 is the User ID
User.find_by_email("david@example.com")  # notice the method being called to search for the email.
User.first  # finds the first User
User.all  # finds all Users and returns them in an array

Two ways to update attributes

user.email = "notDavid@example.com"
user.save

or using update_attributes which performs the update and saves in one step. It returns true if the save was successful.

user.update_attributes(:name => "The Guy", :email => "guy@example.com")
>> true

Model validations

Add validations to your model files.

class User < ActiveRecord::Base
  attr_accessible :name, :email

  validates_presence_of :name
end

The database will now not allow save’s to pass if all validations do not pass. Use the valid? method to check if an object passes all validations.

Don’t forget to use table indexes when searching using a database column or ensuring uniqueness.
$ script/generate migration add_email_uniqueness_index
add_index :user, :email, :unique => true

May 23 10

Rails Tutorial Notes

by Dave

Using Test Driven Development, create your controller using

$ script/generate rspec_controller Users new

Remember to remove the view_specs because we don’t use them.

$ rm -rf spec/views

Don’t forget to integrate views into our Controller spec test so we can test for things like the correct title in our views.

describe UsersController do
  integrate_views
  do ...
    ...
    ...
  end
end

Make sure your tests pass, then commit to git (and push if required)

$ spec spec/
$ git add .
$ git commit -am "Finished layout and routes"
$ git checkout master
$ git merge filling-in-layout
$ git push

Adding debug

debug(params) if Rails.env.development?
May 18 10

Rails relevant Ruby

by Dave
stylesheet_link_tag 'blueprint/screen', :media => 'screen'

Blocks can be more than one line, and often are. In Rails Tutorial we’ll follow the common convention of using curly braces only for short one-line blocks and the do..end syntax for longer one-liners and for multi-line blocks.

To inspect an object use the object.inspect method. or p object for short.

May 17 10

Rails Helpers

by Dave

Helpers are functions used in views.

If a helper corresponds to a specific controller, you should put it in the corresponding helper file. For example, helpers for the Pages controller generally go in app/helpers/pages.helper.rb.

If the helper is going to be used on all a sites pages then the helper file to use is app/helpers/application.helper.rb.

In the helper file:

def title
base_title = "Ruby on Rails Tutorial Sample App"
if @title.nil?
base_title
else
"#{base_title} | #{@title}"
end
end

In the view:
<%= title %>

May 16 10

Test Driven Development (TDD)

by Dave

When testing Rails applications the favoured test suite is Rspec.

For Ruby versions 1.8.7 and under, the below instructions should get you going.

$ [sudo] gem install rspec -v 1.3.0
$ [sudo] gem install rspec-rails -v 1.3.2

The test folder is now named spec. You no longer need your test folder.

To setup rspec tests for a controller named Pages:
$ script/generate rspec_controller Pages home contact

Your test file pages_controller_spec.rb will contain a test looking like the following:

describe "GET 'home'" do
it "should be successful" do
get 'home'
response.should be_success
end
end

The first line is a description. The second line is also and neither have any effect on the test. The third line performs a GET request to the page. The fourth line describes the desired result. should_be_success looks for status code 200.

To run your tests:
$ spec spec/

Red, Green, Refactor

This is the process you work through when following Test Driven Development. First get the test to fail, then to pass, then refactor your code.

May 5 10

Heroku for Deployment

by Dave

Setup an account at Heroku

Create a new application at Heroku
$ heroku create

Deploy your app
$ git push heroku master

Open your app
$ heroku open

Rename your subdomain
heroku rename appnamehere

May 4 10

Git

by Dave

Git is a version control system which allows you to track changes to projects code amongst many other things.

First-time system setup

Do these steps once per computer.

Head over to Installing Git section of Pro Git and install Git.

$ git config --global user.name "Your Name"
$ git config --global user.email youremail@example.com
$ git config --global core.editor "mate -w"

(this last line is if you’re using textmate)

Setting up a NEW Repository for your App

Generally you will setup a repository for each application you create.

1. Initalize the repository

$ git init
Initialized empty Git repository in /Users/username/rails_apps/first_app/.git/

2. Add the project files to the repository (but ignore some first!)

By default Git tracks the changes of all files, but there are some we don’t want to track. For example, the log files. We ignore files by including a file named .gitignore in the Rails root directory. Generate this file using your text editor and here’s a sample of what you might put in it.

log/*.log
tmp/*
tmp/**/*
doc/api
doc/app
db/*.sqlite3
*.swp
*~
.DS_STORE

Now we may add files to Git.
$ git add .

The dot ‘.’ represents the current directory and Git is smart enough to add the files recursively so it automatically adds all subdirectories. This places the projects files in a staging area. You can see what files are in the staging area using the status command.
$ git status

3. Committing files to the repository

To tell Git you want to keep the changes in the staging area, use the commit command.
$ git commit -m "Initial commit"

The -m lets you add a message for the commit.

Remember, Git commits are local, recorded only on the machine on which the commits occur.

To push the changes to a remote repository you must use git push.

Branch, Edit, Commit, Merge

When making changes to an application use this process.

1. Checkout a Branch


$ git checkout master
$ git checkout -b 'branch name'

Notice the -b flag for checking out a branch. The first line just ensures we are branching from the master.

git branch will list all the local branches, with an asterix identifying which branch we’re currently on.

2. Edit

Edit your files as required.

3. Commit

If you’ve added new files make sure you use git add . prior to doing a commit. Otherwise you may use the -a flag with your commit if you’ve modified existing files.
$ git commit -a -m "comment goes here"

4. Merge

When finished making changes, you merge these back to your master branch.
$ git checkout master
Switched to branch 'master'
$ git merge modify-README

Change modify-README to the name of your branch.
Afterwards you can tidy up your branches by deleting the topic branch.
$git branch -d modify-README

Push your changes to a remote repository

Use the push command
$ git push

May 3 10

Learning Ruby and Rails Notes

by Dave

Strings

Strings are surrounded in quotes. For example, "David" is a string.

A complete list of Ruby string methods is here.

.reverse
"David".reverse
>> "divaD"

.length
"David".length
>> 5

.strip
Removes white space around a string.
"David ".strip
>> "David"

multiplication
"David" * 5
>> "DavidDavidDavidDavidDavid"

Converting Object Types

.to_s – converts to strings
.to_i – converts to integers
.to_a – converts to arrays

Arrays / Lists

Use brackets [].
[12, 47, 35]

.max
[12, 47, 35].max
>> 47

Hash / Dictionary / Associative Array

A hash is when you want to associate one thing with something else, like a dictionary. These are called Key, Value pairs.
Hashes use curly braces {}.

food["Fish"] = :yum
food["Dog"] = :yuck
food["Beef"] = :delicious

food
>> {"Fish" => :yum, "Dog" => :yuck, "Beef" => :delicious}
rating
food.keys
>> ["Fish", "Dog", "Beef"]

Blocks

Using the above example of food, you may use a block like the following to tally your results.

books.values.each { |rate| ratings[rate] += 1 }
>> [:yum, :delicious, :yuck]

ratings
>> {:yum => 1, :yuck => 1, :delicious => 1}

Another example of using a block:
5.times {print "Yes!"}
>> Yes!Yes!Yes!Yes!Yes!

Classes

String, Array, Hash are all examples of Classes.

Creating a class
class BlogEntry
attr_accessor :title, :time, :fulltext, :mood
end

attr_accessor is how you define variables, or in this case attributes attached to a class.

Let’s start a new entry.
entry = BlogEntry.new
entry.title = "Hello world!"
entry.fulltext = "Yes this is my first post!"
entry.mood = :sick
entry.time = Time.now

The initalize Method
Using the initalize method you won’t have to type the time every post.

class BlogEntry
def initalize( title, mood, fulltext )
@time = Time.now
@title, @mood, @fulltext = title, mood, fulltext
end
end

Important things to notice
Outside the class we use accessors: entry.time = Time.now. But inside we use instance variables: @time = Time.now.

Apr 12 10

Tim Ferriss – How to prepare for Public Speaking

by Dave

http://www.fourhourworkweek.com/blog/2010/04/11/public-speaking-how-i-prepare-every-time/